Solid Principle : Open Closed Principle (OCP)

I have already discussed Solid Principle : Single Responsibility Principle (SRP), today I am going to discuss the second principle of SOLID i.e. Open Closed Principle.

Open Closed Principle (OCP)

Almost everyone who have done some sorts of db involvement work are somehow familiar with the acronym CRUD. When we start working/designing a class we usually set our mindset that we are also doing CRUD operation to classes as well. i.e.

  • C -> Create a class
  • R -> Read from that class
  • U -> Update the class to fit our business need
  • D ->Delete the class when we don’t need that anymore.
Heads Up:

If you are designing  your class in such that it works like CRUD then you are doing it wrong!

The open closed principle (ocp) states that –

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

That means, you are not allowed to do any modification(update or delete) of your existing class!  So, CRUD point of view soon changed into this –

  • C -> Create a class
  • R -> Read from that class
  • U -> Update the class to fit our business need
  • D ->Delete the class when we don’t need that anymore.

As you can see OCP basically imposed 2 certain constraints that you should have to follow. Now, you might be wondering why they prefer to follow certain restriction while designing a class. This is because it is assumed that the existing code (which might be already in production!) have already been reviewed and passed the unit test once. So literally we should not try to modify those existing code unless its mandatory coz if you make any changes on your existing  code base then that will require your code to gone through those process which is not only time consuming but also comes with some extra expense.

That’s why the preferred way of writing code is following the OCP principle. This ensures you code is extensible enough so that you only have to write it once and not have to change it later each time a new requirement comes.

Of course there might be situation where you will be forced to violate OCP principle and that is ok because after all we don’t want bugs to stay there on our code base forever. On such scenario you will make modification as much as needed but just keep the SOLID principle in mind.

Implementing OCP is pretty straight forward. First try to implement the SRP on your code base. This will separated each class with its own responsibility. The next step is to abstract these responsibility(concerns) and let consumers of these concerns talk to these abstraction.

Let me come up with a code example to give you an overview of OCP. If you google for OCP example almost everytime they come up with a Rectangle, Circle example. Here I am presenting a different scenario.

The above code snippet calls the generic GetAsync<T>(string EndPoint) method to fetch the mailchimp campaign analytic report. If you check the implementation of GetAsync<T>(string EndPoint) method you will see that under the hood its using HttpClient() class. Check the below code:

Now, assume after a certain period of time, you want to give a try to RestSharp (because RestSharp is opensource and it supports auto serialization as well).

Now, you can certainly create a new class that would expose method which would do GET request with RestSharp. Then you need to make changes to MailChimpReportsOverview class to point the new class. But you are not allowed to do so because OCP states you are not allowed to make modification.  So the only options you are left with is  BaseOperation class. Again changing to this class would also violate OCP! Plus it already has a implementation for HttpClient(). 

So as you can see the whole design that we have been using so far violates the OCP , plus its not easily extendable as well.

Solution :

The solution is simple. To bring the concept of interface, here is simple walk through.

Reference :

Solid Principle: Single Responsibility Principle (SRP)

So, its been quite long I have not been doing any blogging. I thought and I really would wish to start  my blogging with Azure Webjobs series but in my way of writing a student from this event asked me some questions that worth me writing this article.

SOLID principle is one of coolest and sexist topic that you as a smart developer should be aware while coding to remove code smells.

The principles that make up the acronym are as follows:

Acronym Principle Principle defined
S Single Responsibility Principle A class should have one, and only one, reason to change.
O Open/Closed Principle You should be able to extend a classes behavior, without modifying it.
L Liskov Substitution Principle Derived classes must be substitutable for their base classes.
I Interface Segregation Principle Make fine grained interfaces that are client specific.
D Dependency Inversion Principle Depend on abstractions, not on concretions.

In this post I am going to discuss about Single Responsibility Principle (SRP).

Single Responsibility Principle (SRP)

Freshers, recent graduates who don’t have industrial working experience they often mixed up responsibilities and usually prefer to write them under one single class. For this very reason, soon their All-In-One class become a big pile of mess. Those class become fragile and non-reusable. So, when new requirement appears they just can’t extend their application in an easy way. Rather they need to make changes on many places. This process is not only error-prone  but at the same time its time consuming as well.

Now, the obvious question is why they prefer or i would rather say why most of them mastered on this style. The answer is simple.

  1. Such system is easy to built and
  2. While designing the system  they did not bring one vital point in consideration i.e. “A system requirement can change over time”.

When a class has more then one responsibility it clearly indicate that the class has more then a reason for change! At its worst changes to any one of the responsibility may prevent the class to pass all the regression test. This kind of coupling leads to fragile designs that may break in unexpected ways when changed.

Let me come up with one code sample that violate this principle.

The main responsibility of the above class is to Get campaign reports from mailchimp server. But as you can see the class is doing lot more then this. Inside the try block it first trying to authorize the current connection.  Once the connection is established its downloading the campaign analytic report from the specified endpoint. It also deserializing the result. In case of failure it also doing some basic logging for future diagnosis.

To solve this issue one should strive with “Single Responsibility Principle” aka SRP. It states that –

A class should have one, and only one, reason to change.

This means you should break your All-In-One class into so many pieces of class unless each of the class holds only one(single) responsibility. Now, as we all agree to break our class in such that it holds only one responsibility the next question is how do we determine if a class has more then one responsibility. Sandi Metz, the author of Practical Object-Oriented Design in Ruby (POODR) mentioned a nice trick. To describe a class if you have to use words like “and” or “or,” you’re most likely breaking the Single Responsibility Principle (SRP). If you have to use the word “and” your class has at least two responsibilities. On the other hand, If you have to use the word “or,” the class likely has more than one responsibility, and there is a good chance that these responsibilities aren’t related to one another.

In brief, anything that gives a class a reason to change can be considered as a responsibility.

Enough talk! Lets refactor the existing code base to fit in SRP.

As you can can see the above code now have only one responsibility. I have extracted other responsibility into their own class.

Extracted class shown below :

Heads Up:

As you keep following the SRP, you will end up with a good number of classes. Beginner often find it little bit difficult to expose this huge number of classes to its end client. One way to deal with this issue is to add a new abstract layer, this is something beyond the scope of this article.


Following the SRP each concrete class become very specific. It not only keeps the classes small and focused but it also makes them easier to understand.