Open closed vs Single responsibility

2.9k views Asked by At

I was looking into the Single Responsibility Principle(SRP) and Open Closed Principle(OCP).

SRP states that a class must have only one reason to change. OCP states that the class must be closed for modification but open to extension.

I find that to be contradicting. One principle states that the class must be simple enough, that you change for a single reason but the other principle states that a class must not be changed but only extended.

Does anyone have a better explanation?

2

There are 2 answers

0
sanderarts On

The Single Responsipbiliy Principle deals with the fact that if a class has multiple responsibilities, these responsibilities will be tightly coupled if they're in a single class. So if an interface or algorithm changes for one responsibility it will likely also effect the other responsibility, an undesired effect.

In the Open/Closed Principle a class should be able to extend its behaviour without the need to modify the class itself. The only need to modify the class should be because it has a bug/error in it, not because you would like to change or add functionality.

For example (OCP): a class that holds a list of hard-coded types of objects is not open for extension, because if you would to add a new type to the list, you would need to modify the class. Instead a better design is when the class has an add or remove functionality, or an interface which you can implement to hold different types per subclass.

0
przemo_li On

Lets represent all the responsibilities and reasons for change as a 2D cicrle.

SRP -> asks us to chip at the edges (haha) of that circle so that what is left is very tightly coupled, and if it will change it will change all at the same time.

OCP -> asks us to poke holes in that circle, so that those parts that will change at different pace can be provided at a latter date.

In other words SRP compliant class may fail OCP and OCP compliant class can fail SRP. There is also significant overlay between the two, but my presentation also shows that there will be differences too.