Similarities and Code
What are the possibilities when implementing similar things?
Handling similar requirements is bread and butter for software engineers. There is a number of ways one can implement similar abstractions and an important aspect of the process is to make an informed decision on which way to choose. My goal in this short story is to briefly highlight the main four ways of dealing with similarity in object-oriented programming and to spark some interest in good programming practices with a short comment and a selection of links to redirect your attention to more detailed articles.
- Code duplication — create two separate abstractions, that are very similar, but don’t share code.
- Flags — create a single abstraction encapsulating both shared and a combination of flag-specific code.
In some cases, it’s all that we need, but on the other hand, it lacks some separation of concerns⁵, increases the volume and can lead to an ambiguous interface of the class. You may also get in trouble if you expect to have more similar abstractions in the future⁶.
- Subclassing (or template method pattern⁷) — create a base class with shared code and two sub-classes that are allowed to override the base implementations.
In some cases, it’s a very good approach. On the other hand, the coupling is high⁸, there is a risk of getting into a fragile base class problem⁹.
super can also be abused if not taken with care.
- Composition (or strategy pattern¹⁰) — create an abstraction with shared implementation and two entities that provide a use-case-specific behavior.
That’s a brief summary of four available methods. As you can see there is no single “best” choice. The answer usually is “it depends” and requires a decision maker to consider the big picture. Let me keep this story short for now though. I’ll build upon it in the future stories.