Open Closed Principle -SOLID design principles

Share the Article

What is Open/Closed Principle

Open/Closed principle is one of the most important principle for object oriented application designing. It is also contributing second letter “O” in SOLID acronym where O stand for Open/Closed. This principle tries to address future modifiability and maintainability issues of an application. Main idea of this principle is to achieve new modifications without impacting existing classes.

As clear from name, “Open/Closed” principle insists to design classes, such that classes are open for extension but closed for modification. Means we should design our class such that, modifications of existing classes for new features should not be possible. We need to extend the existing classes and support modification.

To get better results, our classes should support “Single responsibility” principle also. With Open/Closed principle, modifications is very easily achieved with better testability feature.


Lets us try to understand the need of Open/Closed principle by taking an example of an application whose job is display video in formats such as:

  • Black & white
  • Colored

Example not using Open/Closed Principle

Lets us try to create an application without using the principle first.

Below is the sample application:

#include<iostream> //main header for io using namespace std;//for namespace enum VideoFormat { BLACK_WHITE, COLORED }; class DisplayVideo { public: DisplayVideo(string v) { cout<<" Video input received"<<endl; } void displayVideo(VideoFormat format) { switch(format) { case BLACK_WHITE: cout<<"Video displayed Format BLACK_WHITE" << endl; break; case COLORED: cout<<"Video displayed Format Colored" <<endl; break; default: break; }; } }; int main() { DisplayVideo d1("Input video"); d1.displayVideo(BLACK_WHITE); return 0; }

Suppose in future, we get requirement to support following new formats also:

  • HD
  • Ultra HD

Since, above class DisplayVideo already handles 2 formats – Black/White and Colored. Therefore, we will go and update existing class as below:

class DisplayVideo { public: DisplayVideo( string v) { cout<<" Video input received"<<endl; } void displayVideo( VideoFormat format) { switch(format) { case BLACK_WHITE: cout<<"Video displayed Format BLACK_WHITE" <<endl; break; case COLORED: cout<<"Video displayed Format Colored" <<endl; break; case HD: cout<<"Video displayed Format HD" <<endl; break; case ULTRAHD: cout<<"Video displayed Format Ultra HD" <<endl; break; default: break; }; } };

Drawbacks of above approach is that we have updated the existing class DisplayVideo. Who all are using Display Video will get need to get update . Plus, we need to update existing test cases also .

With above approach, both development and testing efforts got increased.

Open/Close principle is the best fit if we want to save efforts for both development and testing.


Let try to update the above class as per Open/Closed.

Thumb Rule – Classes should be open for extension and should be closed for modifications. We need to follow these rules :

Design an Abstract class and a member function

Firstly, create an abstract base class as DisplayVideo and and expose interface – displayVideo as below. Since Display video is an abstract class we have achieved now close for modification.

class DisplayVideo { public: virtual void displayVideo()=0; };

Provide concrete implementation of base class

Secondly , extend all format from DisplayVideo so that based on user request particular format can get displayed. We have achieved Open for modifications with this.

class DisplayVideo { }; class DisplayVideoBlackandWHite : public DisplayVideo { }; class DisplayVideoColored : public DisplayVideo { }; class DisplaYVideoHD : public DisplayVideo { };

Same Example now using Open/Closed Principle

Below is the updated application code with support for HD also:

#include<iostream> //Main header for io using namespace std; //for namespace class DisplayVideo { public: DisplayVideo(string v) { cout<<"Video input received"<<endl; } virtual void displayVideo() = 0; }; class DisplayVideoBlackandWHite: public DisplayVideo { public: DisplayVideoBlackandWHite(string v): DisplayVideo(v) { } void displayVideo() { cout<<" Video displayed Format BLACK_WHITE"<<endl; } }; class DisplayVideoColored: public DisplayVideo { public: DisplayVideoColored(string v):DisplayVideo(v) { } void displayVideo() { cout<<" Video displayed Format Colored"<<endl; } }; class DisplayVideoHD: public DisplayVideo { public: DisplayVideoHD(string v): DisplayVideo(v) { } void displayVideo() { cout<<" Video displayed Format HD"<<endl; } }; int main() { DisplayVideo *d1 = new DisplayVideoBlackandWHite("Input video"); d1->displayVideo(); delete d1; DisplayVideo *d2 = new DisplayVideoHD("Input video"); d2->displayVideo(); delete d2; DisplayVideo *d3 = new DisplayVideoColored("Input video"); d3->displayVideo(); delete d3; return 0; }

So, if in future we need to support Ultra HD format just extend Display Video for Ultra HD. No updation on client logic. Plus, for testing just need to write new test cases for Ultra HD class. No impact on existing test cases.

Pros & Cons of Open/Closed Principle


  • Easy to introduce or modify feature with less efforts.
  • Testability is very easy due to sub modules addition.


  • Due to addition of one more abstract class code complexity increased.

Main Funda: Open/Closed Principle ensures that a class remain open for extensions but closed for modifications.

Advanced C++ Topics

Single Responsibility Principle
Singleton Design Pattern
Factory Method Design Pattern
Builder Design Pattern
How std::forward( ) works?
How std::move() function works?
What is reference collapsing?

Share the Article

8,280 thoughts on “Open Closed Principle -SOLID design principles

  1. lasix drip norfloxacin imiquimod price This is a type of cookie which is collected by Adobe Flash media player it is also called a Local Shared Object a piece of software you may already have on your electronic device to help you watch online videos and listen to podcasts

  2. vitaros 3 mg g krm cena STOCKHOLM, July 24 Reuters World number two truck makerVolvo AB achieved stronger than expected orders andearnings in the second quarter as a recovery in demand gainedpace in nearly all its main markets can i buy viagra at cvs High doses of myo- inositol may have additive effects when taken concurrently with selective serotonin reuptake inhibitor SSRI and selective serotonin norepinephrine reuptake inhibitor SNRI antidepressant medications

  3. Swimming can be a matchless form of worry, as it works many disparate muscle groups and can be unhurried on the joints. Even so, it is influential to be informed of any salubrity conditions or precautions that may use your ability to swim safely. If you have any concerns, it’s pre-eminent to consult with a doctor preceding pleasant in any swimming activities.
    It’s also vital to be aware of limited swimming regulations and guidelines, as spring as the policies of the swimming masterliness you plan to visit. Bitly – Click here!..

  4. No matter what, unnamed industries and professions show to be in turned on bid in the city. It’s superior to note that the conquer caper let out for you drive depend on your skills, observation, and interests. It’s also substantial to research and weigh the responsibility stock exchange, compensation, and benefits of the energy or profession you are in view of before making a decision. Bitly – More info!..

  5. The comment section about a casino may contain tons of negative thoughts even when the casino is objectively top-notch. That occurs because unfortunate players make irrational decisions. They might also chase losses without revising the rules. Regardless of that, the casino administration must be attentive to everyone. It must attend to irrational and even hysterical guests. If the administration neglects negative comments, neglect the casino. Luke is a media graduate who is looking to build upon his experiences from his strong love of sports betting and casino games which started during his first year of college. His fresh mindset always brings new content ideas to the team and his editorial skills will continue to grow with the help of the upper management team at Crypto Wild continually offers new bonuses and is adding new cryptocurrencies for their customers. Crypto Wild is offering a Welcome Bonus up to 150% + 150 Free Spins. Fortune Jack is thanking its new customers with 25 Free Spins with no deposit All you need to do is really as simple as it gets: just enter your email ID and click on 1-Click Sign Up, and we create an account and a free bitcoin wallet for you! There are no deposit limits, and we give you 3 withdrawal options: automatic weekly withdrawals, regular withdrawals and instant withdrawals. A Bitcoin Casino Bonus has more similarities than differences when compared with any other bonus offer that is claimed using any other payment method. These days the top online casinos from the United States and Australia (‘Aus’ in popular terms) offer some great Bitcoin Bonuses to all its new and existing players. Players can choose any of the online gaming site where Bitcoin is accepted for making payments. After that, look for the exclusive bonus offers and select Bitcoin as your method of payment to bag those promotional offers right away. Also, sometimes Bitcoin Casinos also offer specially crafted Bitcoin Bonuses to its players so that they win big and in the easiest way possible.

  6. Having read this I thought it was very enlightening. I appreciate you taking the time and energy to put this content together. I once again find myself personally spending a lot of time both reading and posting comments. But so what, it was still worth it!

  7. After checking out a few of the blog articles on your web page, I truly like your technique of writing a blog. I bookmarked it to my bookmark site list and will be checking back soon. Please check out my web site as well and tell me what you think.

  8. Siz tıraş makinesi önerisi istemişsiniz ama ben size genede jilet
    öneriyorum. Permatiğin önündeki plastik ucu kırarak rahatlıkla kılları kesebilirsiniz.
    Önündeki ucu kırdığınız zaman eğer dikkatli olursanız
    zaten kanatmadan, kesmeden rahatlıkla tıraş edersiniz kılları.
    Ben yıllardır hep jilet.

  9. Oh my goodness! Amazing article dude! Thank you so much, However I am encountering troubles with your RSS. I don’t know why I can’t subscribe to it. Is there anyone else getting similar RSS problems? Anyone who knows the answer can you kindly respond? Thanks!

  10. hello there and thank you to your information – I’ve definitely picked up something new from right here. I did however experience a few technical points using this website, since I experienced to reload the website a lot of occasions previous to I may just get it to load correctly. I have been considering if your hosting is OK? No longer that I am complaining, however slow loading instances occasions will very frequently affect your placement in google and could injury your quality score if advertising and ***********|advertising|advertising|advertising and *********** with Adwords. Well I’m adding this RSS to my e-mail and could glance out for much extra of your respective exciting content. Ensure that you replace this again soon..

  11. Write more, thats all I have to say. Literally, it seems as though you relied on the video to make your point. You clearly know what youre talking about, why waste your intelligence on just posting videos to your blog when you could be giving us something enlightening to read?

  12. The next time I learn a weblog, I hope that it doesnt disappoint me as a lot as this one. I imply, I know it was my choice to learn, but I really thought youd have something attention-grabbing to say. All I hear is a bunch of whining about something that you might fix in case you werent too busy looking for attention.

  13. With havin so much content and articles do you ever run into any problems of plagorism or copyright violation? My site has a lot of exclusive content I’ve either authored myself or outsourced but it appears a lot of it is popping it up all over the web without my authorization. Do you know any solutions to help reduce content from being ripped off? I’d genuinely appreciate it.

  14. It’s perfect time to make a few plans for the future and it’s time to be happy. I have read this submit and if I may just I want to counsel you few fascinating issues or advice. Perhaps you could write subsequent articles regarding this article. I desire to learn more things about it!

  15. Hi, There’s no doubt that your site might be having web browser compatibility problems. Whenever I take a look at your web site in Safari, it looks fine but when opening in IE, it’s got some overlapping issues. I just wanted to provide you with a quick heads up! Besides that, fantastic website.

  16. You made some good points there. I looked on the internet for additional information about the issue and found most individuals will go along with your views on this website.

  17. Aw, this was an exceptionally good post. Taking a few minutes and actual effort to create a great article… but what can I say… I procrastinate a whole lot and don’t manage to get nearly anything done.