Some words on software design

This post is rather technical, so skip it, if “overloading” primarily means severe working conditions and/or electrical circuit malfunction to you.

Two cool ideas that come from functional programming are

  • compile-time type safety
  • generic interfaces

They are very important when you try to design a library since you very often do not want incorrectly typed code to compile, which is somewhat hard to achieve since the OO world likes runtime dispatching, which may force you to impose too weak constraints on the types. Let me give an example of what I am talking about:

So what if we want to have a specialized Processor for some specialized Things? We probably will have to resort to runtime checks (in C++, you would use dynamic_cast, in Java, it would be instanceof) and throw an exception. Which is theoretically okay, but not really needed. The problem is that we mostly create the Dispatch class instance in compile-time and could control type safety without resorting to exceptions.

My idea was to replace the whole AbstractFactoryOfThings stuff with simpler specifications, like template-parameterized function objects that create Things because they are a subclass of some Factory. This way, the Dispatch class becomes Dispatch and we can safely mix and match the factory and the processor function objects without being endangered by runtime exceptions.

The whole thing comes with a price: You cannot mix the factory and the processor as a function of user input (theoretically, you can, but you have to construct all valid combinations first) anymore. Which can be annoying, but, if you design a library where Thing is something that should never be altered at runtime (like a fixed presentation), the described approach is perfectly sensible. Moreover, it generates less boilerplate code, since you do not have to come up with specific interfaces for Factory and Processor. They can be some sort of pre-defined Function<In, Out> classes.

One Reply to “Some words on software design”

  1. Hey, it`s good to see that you came to the same conclusion like me 🙂
    I faced the same problem some time ago. In c++, you have the benefit of a really generic type system. You can just use methods of the generic type and the compiler will match them to the real type (or complain, if not possible).

    However, I was developing in Java (yeah, what a pity!). Perhaps I was just dumb, but I could not find a way that really convinced me. The problem is that you need interfaces for every method you want to use in a generic type. This seems to be more OO, but unlikely breaks the whole cast-free, type-safe and dynamic implementation that you propose here, mainly because as a library developer you don`t know what classes or interfaces your library will be used with.

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.