Stop Breaking the OCP. What you can do when you’re breaking… | by Catalin Patrascu | Aug, 2022

What you can do when you’re breaking the OCP principle from SOLID

Photo by Tim Mossholder on Unsplash

One of the most common questions in technical engineering interviews is: what is S.O.L.I.D and if you can provide some examples for each principle.

There are lots of resources that preach how SOLID should work. However, in practice, the devil is in the details.

What is it?

Objects or entities should be open for extension, but closed for modification.

This means that an entity should be extendable without modifying the entity itself.

The number one sign of violating OCP is using if-else or switch statements. As a side note, any branching of if-else or switch should raise a small question mark for a possible code smell.

Examples of situations you may find in your code base:

Imagine that the business requirements change, and you need to add an AnalyticsLogger that will record in GoogleAnalytics or in FacebookAnalytics .

Your Logger class is open for extension, but at the same time, it will also be open for modification (since you actually need to add a new switch case), which violates the OCP.

Let’s see another example:

Choosing between different storage possibilities with an if-else branching logic: first and foremost, a bad code smell is using string literals that are not constants or enums: so many bad things and bugs can result from it, but that’s another story.

Let’s say the Product Owner comes after one month and wants the ability for the app to store something in memory instead of the two persistent ways. What happens then? Another else if case scenario and, later on, another one, and so on.

Other scenarios may be, but are not limited to:

We can clearly see a pattern emerging here.

Now the natural question is, how do we fix it? How can we prevent it?

All the possible implementation scenarios should conform to some abstraction (interface, protocol, etc.), and the decision-maker of the proper implementation should be moved higher in the chain of responsibility.

To illustrate this in the example with the StorageService, we will use a behavioral design pattern called Strategy .

If you look closely at line 32 and then at lines 38–40, we can conclude that StorageService entity is now “locked,” closed for modification, and open to extension. Lines 38–40 show us that we can add how many new storage methods we need and not change the code inside the StorageService.

Now, we’re back on track for a clean architecture with a simple code shift dictated by a design pattern.

Since a picture is worth a thousand words, I will provide a visual representation of how a simple change in the code has implications on so many levels if the code base has not been architected and built properly for scalability.

Source: Dave Nicolette

Thanks for reading!

Stay tuned for more.

News Credit

%d bloggers like this: