O-Open Closed Principle (For English Readers)

Tuba Saday
Delivery Hero Tech Hub
2 min readOct 14, 2021

Have you ever wished that you would change your somewhere? For example, your hair, eye color, height, skin color?

Unfortunately, we do not have such an ability for our body in this century, but we can bring this ability, which we wish to, into our codes.

Root of the OCP:

Bertrand Meyer defined this principle in his book Object Oriented Software Construction in 1988. Meyer argued that the OCP principle should be implemented by inheriting it through abstract classes. In 1996, unlike Meyer, Robert Martin mentioned in his book that OCP should be implemented with implementation through interfaces because inheritance creates tight coupling.

So what is this Open and Close?

A module is open if it is suitable for extension (if it is possible to add fields or a new function to data structures), and if we can use this module by other modules without any changes, this module is closed.

“Software entities (classes, modules, functions, etc.)
should be open for extension, but closed for
modification.” by Robert Martin.

Let’s say we have an Employee class, and inside this employee class, we have a method called work. It has some sort of workflow in it. This flow belongs to a software engineer, let’s say we hired a tester, we will need to write what this tester needs to do in this work method, then we hired an analyzer and changed our work method again. It will go on like this, when we add a new responsibility to our work method or fix a bug, we will never know where this code will affect, and if the improvements we made to the work method in the past take 1x time, this development time will increase as time goes on.

How to implement OCP:

We can implement OCP with 3 methods:

First, let’s see our smelled code:

1 — Parametric Solution:

2 — Inheritance Solution:

3 — Injection Solution:

As you can see, when we organized our bad code design according to OCP, we eliminated the switch case. Now, when a new employee type is added, we will not need to edit the switch case in our Work method (closed to change) and the Employee class or IEmployee interface can be used without causing any error in newly added employee types, and if desired, new responsibilities can still be added to the Employee class or the IEmployee interface (expansion). open).

--

--

Tuba Saday
Delivery Hero Tech Hub

It’s a non stoppable learner and an insane developer.