SOLID one by one — O

Date — 14/Sep/2018

rahul reddy
2 min readSep 17, 2018

This is the third post in the series of posts on Solid. In this I will explain the second principle in SOLID, O. It stands for Open Closed principle. The most popular definition of Open Closed principle is as below:

The open/closed principle states “software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification

The general idea of this principle is to write code so that you will be able to add new functionality to it without changing the existing code. Robert C. Martin considered this principle as the “the most important principle of object-oriented design”. Bertrand Meyer was the one who proposed this idea. Meyer’s proposed method for maintaining open closed principle relied on the inheritance. The explanation was as bellow:

A class is closed, since it may be compiled, stored in a library, baselined, and used by client classes. But it is also open, since any new class may use it as parent, adding new features. When a descendant class is defined, there is no need to change the original or to disturb its clients.

But later on other authors like, Robert C. Martin in his articles about the SOLID principles or Joshua Bloch in his book Effective Java,taught inheritance introduces tight coupling if the subclasses depend on implementation details of their parent class.

To avoid this they proposed the use of polymorphism and interfaces instead. Using interfaces instead of superclasses to allow different implementations in different sub classes, thus reducing the coupling and providing an extra level of abstraction at the same time. This follows the open closed principle because interfaces are closed for modifications, while one can extend them to provide new implementations thus making them open for modifications.

An example of open closed principle violation can be branch on types. In case of branch on types a software entity cannot be open for extension without being modified.

--

--