SOLID – Open/Closed Principle

I liked this explanation of Open/Closed principle from SOLID
https://adevait.com/software/solid-design-principles-the-guide-to-becoming-better-developers

Open/Closed Principle

Open/Closed Principle is the most confusing one of the 5 principles when you judge by the name. How can something be open and closed at the same time? However, it has a fairly simple idea behind it and it’s the one that can save you the most development time if you apply it correctly.

The Open/Closed Principle states that a module should be open for extension, but closed for modification. That means you should be able to extend a module with new features not by changing its source code, but by adding new code instead. The goal is to keep working, tested code intact, so over time, it becomes bug resistant.

Applying the Open/Closed Principle is like working with an open source library. When you install an open source package in your project, you don’t edit its code. Instead, you depend on its behavior but you write your code around it. At one point, the library gets tested so much that it becomes very stable. This is the approach you should take with your own code: add new features as new pieces of code that cannot break what’s already working.

How to make sure your code follows the Open/Closed Principle?

Let’s say you need to implement an e-commerce module with multiple payment options. You can create a class Pay and add different payment options as separate methods. This would work, but it would result in changing the class whenever we want to add or change a payment option.

Instead, try creating a PayableInterface that will guide the implementation of each payment option. Then, for every payment option, you will have a separate class that implements that interface. Now the core of your system is closed for modification (you don’t need to change it every time you add new payment option), but open for extension (you can add new payment options by adding new classes).

And it finally clicked for me, the above example:

You can achieve Open/Closed principle by extracting an interface over your behavior.
The interface will specify the what  a needs to be done, and by doing this your code is closed for modifications, I mean… you rarely change the rules once you have extracted them. And having classes implementing the interface, the concrete implementation contains the how it is done.
So you can add different implementations – and thus you achieve the open for extension

Here is another great link on the subject
https://khalilstemmler.com/articles/solid-principles/solid-typescript/#OCP

Leave a comment