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.
Two separate abstractions

Sometimes, it’s good enough¹. On the other hand, duplication of code is evil². It usually leads to code that is hard to analyze³ and modify.

  • Flags — create a single abstraction encapsulating both shared and a combination of flag-specific code.
Two abstractions in one

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.
Base class and two subclasses

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. self and 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.
Abstraction and two specializations

In some cases, it’s an approach worth taking¹¹. It is the most decoupled¹² and clean approach to the problem. On the other hand, it’s a bit more expensive than subclassing.

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.

Thanks for the beautiful images to my friend Radek.

I’m Maciek Czarnik

iOS Developer, musician, maker. Passionate about building beautiful, robust, useful and user-friendly apps. Contact for project inquiries.