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.

Why

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.

How

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

Pros

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

Cons

  • 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

2,274 thoughts on “Open Closed Principle -SOLID design principles

  1. This deep cleaning checklist can be followed every three to four months, with some exceptions like cleaning the kitchen, changing your sheets and vacuuming rugs. You should be thoroughly cleaning your home as the seasons change, paying special attention to spring cleaning once cold and flu season is wrapping up. “To get the time down, you have to be consistent—that’s the whole premise,” Sardone says. “You do the same thing every time you clean, so it is a routine. The routine is the method, and that is an inherently better way to clean because the speed comes from the method instead of from hurrying. You really can clean your house in half the time. It’s not a gimmick.” Editor's Tip: Keep extra trash bags in the bottom of your wastebasket. When it's time to empty it, you'll have liners handy after you've removed the existing trash bag. https://www.educationalaids.in/community/profile/meaganpilpel661/ At NJ’s Cleaning World Inc., our company is determined to please you with our amazing cleaning services. We know how happy it makes you when we come in and clean your home. For this reason, we absolutely love what we do and we love helping our customers! “I’ve been using their services for over 6 years, fair price for the quality of services. I basically have unconditional trust with Chris, not only with his services but also, with my personal documents and other. Recommend 100%.” They did a fantastic deep clean. $80 hr. We have a 2Bd 2Ba apartment. They also cleaned the fridge, oven & microwave; $220 all together. And no gross cleaner smells because they use all natural cleaning products. 🙂 We at Maid Spotless Cleaning Services understand your world because, we, too have our own family and responsibilities to juggle. Our team of professional cleaners will ensure your home is immaculate, top to bottom. We will wash, clean, dust and mop every surface to ensure your home is warm, clean and smelling fresh for those that matter most to you. And, when you are planning to have friends or extended family over to visit, you can have the confidence knowing your home is spotless and clean at the highest level. Consider our services and let us treat your home like ours today!

  2. Another way to prevent getting this page in the future is to use Privacy Pass. You may need to download version 2.0 now from the Chrome Web Store. Most of us spend a lot of time in our kitchens, whether we want to or not. When you are buying or selling a home, the kitchen design and features is one of the most important factors to consider. If you want to update your kitchen on a budget, there are a lot of easy options (DIY jobs included) that will make a big impact. “Another great place to save is if you know you’re doing a kitchen redesign and you want a really sexy backsplash. Well, you can use $3 per square field tile and use $40 decorative tile. With that $40 decorative tile, you only need maybe six square feet. You can splurge on a small quantity of the expensive tile and place it into a field of way less expensive tile, but the overall result is that it all looks expensive,” Shea suggests. https://rumahpositif.lazispedia.com/community/profile/dominicrobles63/ Give a drop-in tub vintage appeal by paneling its exterior. To guard against rot on wood surrounds, make the deck out of plywood topped by a sheet of waterproof laminate, and cap just the edges with solid stock. Use exterior grade beadboard plywood for the sides, and skirt the bottom with baseboard. In general, having a separate tub and shower in a small master bathroom seems like an impossible scenario. In any case, nothing is impossible with a well-planned layout. Obviously, to fit the two installations into your bathroom and leave enough area to get in and out of your tub and shower, the perfect size of your bathroom ought to be no less than 45 square feet. Name something a plant can’t fix—we’ll wait. While you may be disappointed with certain things in your tiny bathroom that you don’t have the means to fix, like unsightly pipes or a boring cupboard, you can use a plant to take the attention off the area like these California renters did in their bath. What a great small bathroom idea!

  3. magnificent post, very informative. I’m wondering why the other specialists of this sector don’t understand this. You must continue your writing. I’m confident, you have a great readers’ base already!

  4. I don’t even know the way I finished up right here, however I thought this submit was good. I don’t realize who you are but certainly you’re going to a famous blogger if you are not already 😉 Cheers!

  5. It?¦s actually a great and useful piece of info. I?¦m satisfied that you just shared this useful information with us. Please keep us informed like this. Thanks for sharing.

  6. With the recent Bitcoin price surge and the decision of PayPal to avail Bitcoin payment services to its users, the future of BTC looks bright. As BTC and other crypto continue to rise in popularity, they will play an increasingly important role in the gambling world. Once you have some cryptocurrency stashed away, you can qualify for your deposit match using Bitcoin Cash, Bitcoin, Dogecoin, Ethereum, Litecoin, and Tether. Bitcoin is completely legal! However, Bitcoin gambling can be a gray zone because authorities can’t maintain laws and regulations in different countries. We will not go into details on laws in different countries but talk about Bitcoin gambling in general. Serving multi-stage companies on a mission to build the future. Tomorrow, Built Today. medium.com lightspeed-venture-partners https://finnohxn532086.weblogco.com/10964392/bitcoin-casino-no-deposit-bonus-official-site If you’re looking to learn more about how Boku works for gambling purposes, how to deposit in just a few taps on your screen and how to choose the best Boku casinos in the UK, you’re in the right place. We have prepared an easy, in-depth guide on the Boku mobile payment option – what its pros and cons are compared to similar methods and why it’s a viable option for UK players in particular. If you’ve got a mobile phone and some credit on your balance or you pay by monthly bill, then you can enjoy sites that accept Boku betting right away. Qualifying fixed odds bet must be at odds of 1 2 or greater. First ВЈ10 free fixed odds bet plus a ВЈ5 free Total Goals football spread bet will be credited upon settlement of the qualifying bet. Second ВЈ10 free fixed odds bet and ВЈ5 free Total Goals football spread bet will be credited the next day. Offer must be claimed within 28 days of opening. Free bet stake not included in any winnings. See full ts&cs. 18+ begambleaware.org

  7. グラブル Ui改変ツールがストア削除 とうとう不正ツールの大元に対する対応がされたのかな グラブルまとめ三姉妹 グラブルのポーカーを自動化してくれるChromeプラグイン「gbf casino tool」 グランブルーファンタジーのカジノゲーム「ポーカー」を自動化してくれるChromeプラグインのインストール方 会員でない方 ※ツール名を押すと各ツールの詳細へ移動。 〔最近の更新をもっと表示〕 とのことですが、1時間でこの人数ということはツール使用者は結構多そう? グラブルの攻撃力計算機の中からおすすめを特徴付きで掲載。使い方の解説も掲載しているので、武器編成や目標を立てる際の参考にどうぞ。 http://weusmovement.com/community/profile/jeanettemueller/ 具体例にオンラインポーカーの記載はありません。しかし、オンラインポーカーで得た賞金は「 (1) 懸賞や福引きの賞金品」または「(2) 競馬や競輪の払戻金」に該当すると考えられます。 ポーカースターズのトーナメントにおけるメリットとしては、「少ない資金(または無料)で稼げる」「ポーカー自体を楽しめる」ということが挙げられます。 まずはこのページでオンラインポーカーの基礎知識と始め方をマスターだ!オンラインポーカー入門/どうやってプレイする? ところで、初心者と上級者は何が違うのだろうか。刹那的な結果を見ただけでは、どちらが実力者かすら分からないこともあるだろう。しかし長期的に見れば、かならず勝つべくして勝った者、負けるべくして負けた者の差が、明確に表れるのである。

  8. Jos lepo on tuote, joka löydät puuttuu pois teidän uhkapeli, vastike Wilderland slot web-pohjainen niin nyt. Jos haluat kokeilla Kingmakeria, sinun tarvitsee vain kirjautua sisään casumo.com -sivustolle, astua valtaistuinsaliin ja panna tämä VIP-peli pyörimään (Uusi pelaaja? Luo tili Casumolle, niin pääset pelaamaan.) Meistä What the Fox Megaways (important note – do not put a blank space before, after and between operators) Kaikki ilmoitukset Free Reelin Joker To maximize the potential of the AMD Ryzen 3000 and 5000 Series processors, ProArt B550-Creator features faster PCIe® 4.0 x16 slots for high-powered graphics cards as well as PCIe 4.0 and PCIe 3.0 M.2 sockets to support high-bandwidth NVMe SSD RAID for faster content creation. Hinta: 110€ + alv. 24% (136,4€ sis. alv.) http://kadioglukoyu.com/index.php/community/profile/chasityhuxley00/ pokerinsäännöt.com opettaa sinut pelaamaan pokeria. Meiltä löytyvät säännöt niin yleisiin kuin harvinaisempiinkin pokeripeleihin. Muista myös, että voit aina kysyä meiltä, jos jokin sääntöihin liittyvä asia askarruttaa! Kaikkien sääntöjen lopussa on palautelomake, jolla voit helposti lähettää kysymyksesi. Perus pokeripeli jonka säännöt ovat ehkä helpoimmat ymmärtää. Jokaisella pelaajalle jaetaan viisi korttia omaksi. Tämän jälkeen on vain yksi kierros, jolloin pelaaja voi vaihtaa halutessaan pois kaikki tai ei yhtään korttiansa. Panostus tapahtuu ennen ja jälkeen korttien vaihdon. Melko monilla kasinoilla on mahdollista pelata pokeria ilmaiseksi. Kätevin keino löytää tällaiset nettikasinot, on hakea niitä hakukoneen kautta kirjoittamalla hakukenttään esimerkiksi ilmainen videopokeri. Tietenkin löydät myös sellaisia linkkejä, joiden kautta ei todellisuudessa pääse pokerin luokse lainkaan. Erilaisilta nettikasinoiden arvostelu- ja asiantuntijasivustoilta voi löytyä usein vihjeitä ilmaisten pokeripelien osalta. Sinun tule valita joku pokerin versio ja lähteä rohkeasti kokeilemaan. On hyvä opetella alkuun yksi versio. Oma suosikkisi selviää parhaiten kokeilemalla useampia eri muunnoksia, joiden perusidea on kuitenkin melko yhtenäinen.

  9. Comentariu Ofertă cazino, live casino, pariuri live, pariuri online.250 de jocuri disponibile (200 sunt sloturi).Jocuri de cazino disponibile (blackjack, poker, baccarat, ruletă). Printre cele mai populare sloturi de la acest provider se află Danger High Voltage, Monopoly Megaways, Extra Chilli și Lil’ Devil, fără să fie uitate titluri precum White Rabbit, Survivor Megaways, Wild Flowers sau Donuts. În plus, în categoria de jocuri de casino, BTG a contribuit și cu diverse versiuni online de blackjack și ruletă. Evolution Gaming este un furnizor de jocuri de cazino care se axează integral pe jocuri live de casino (inclusiv multiplayer), spre deosebire de majoritatea celorlalți provideri care pun accent în special pe sloturi video. La nivel mondial Evolution Gaming este printre cele mai importante nume în domeniu, furnizând jocuri la zeci de cazinouri din întreaga lume. Printre avantajele principale oferite putem enumera: http://kodeforest.net/wp-demo/disaster-relief/community/profile/jordancritchfie/ Funcţia ‘Depunere Rapidă’ este un mod şi mai rapid de a-ţi finanţa contul Stars şi suportă multe metode populare de depunere, inclusiv Visa, Mastercard şi NETELLER. Caută logo-ul Depunere Rapidă în dreptul metodei de depunere din Casierie. Ţi se va da opţiunea de a face acest cont să fie ‘Cont Depunere Rapidă’, după care transmiţi tranzacţiile direct din joc. Află mai multe despre funcţia Depunere Rapidă. Jocurile online cu jackpoturi ajung la milioane de RON. Având în vedere că ratele de plată online sunt mult mai mari decât cele offline, nu e de mirare că se câștigă des premii uriașe. În cazul în care vrei să vezi unde găsești cele mai mari jackpoturi din cazinourile românești și la ce slots online pot fi câștigate, am pregătit deja pentru tine o listă cu acestea. Intră în pagina Jackpots jocuri cu păcănele și vezi jocurile cu cele mai mari premii!

  10. Was auch immer es mit der Karotten-Sucht auf sich haben mag: auffallen tun die beiden definitiv! Man erfährt auf keinem Kanal, woher das Duo stammt, was es neben Twitch beruflich macht und wofür die freie Zeit draufgeht. Sicherlich haben die beiden ein Privatleben, und möglicherweise sogar ein gemeinsames. Darüber jedoch können wir aktuell nicht viel erzählen, denn Fans bleiben in dem Punkt außen vor. Ich bestätige, dass ich Volljährigkeit (18+) erreicht habe und stimme den Allgemeinen Geschäftsbedingungen von ArgoCasino zu. Um eine Freispiel-Runde in diesem Automatenspiel zu aktivieren, sollten auf dem Bildschirm mindestens 3 Scatter-Symbole erscheinen. Für 3 Scatters erhalten Sie 7 Free Spins, 4 besondere Symbole bringen Ihnen 13 Freispiele, 5 Scatters aktivieren 15 Frei-Spiele und 6 solche Spielsymbole lösen 20 kostenfreie Drehungen aus. Während dieser Bonus-Runde werden auf jeder Walze 7 haftende Wilds aktiviert. Sie können diese Runde ausprobieren, auch wenn Sie Doghouse Megaways kostenlos spielen. http://trevortkzn532087.thenerdsblog.com/14591678/online-casino-echtgeld-erfahrungen Christoph Lübben Als letztes sollten sie dann noch überlegen wie sie den Automaten erhalten. Ein Transport kann durchaus zu einem Problem werden. Wer „nur“ einen Kleinwagen hat, der kann schonmal Probleme bekommen, auch sind die meisten Automaten recht schwer und unhandlich. Überlegen sie sich also früh genug mit wievielen Leuten es sinnvoll ist die neue Erwerbung zu holen und vor allem ob sie überhaupt in den Wagen passt… Durch die weitere Nutzung der Seite stimmen Sie der Verwendung von Cookies zu. Weitere Informationen Akzeptieren + 49 52 51 89 78 0 Wir Bieten hier mehrere Novoline Merkur Spielautomaten mit Spiele an. Die Geräte sind alle Funktionsfähig. Online Echtgeld Casino – Spielautomaten zahlungsanbietern Alle Casinos wurden von den folgenden Parteien als sicher und seriös eingestuft:

  11. “The Company’s executives, collaborating with several celebrity promotors, (a) made false or misleading statements to investors about EthereumMax through social media advertisements and other promotional activities and (b) disguised their control over EthereumMax and a significant percent of the EMAX Tokens that were available for public trading during the Relevant Period,” the complaint reads. Unlike Bitcoin, Ethereum has no limits on its total amount. There is a max cap on Bitcoin of 21 million, but such restrictions do not apply to Ethereum. Over 120,426,128 ETH are in circulation as of April 2022. It’s now time to shop for your first NFT! So make sure you’ve connected your MetaMask via the profile button on the top right-hand corner. You can then use the search box if you are looking for a specific collection or browse the trending NFT projects shown on the home page. https://selfken.com/community/profile/frieda49p179292/ We propose a model of how multiple societies respond to a common crisis. A government faces a “damned-either-way” policy-making dilemma: aggressive intervention contains the crisis, but the resulting good outcome makes people skeptical of the costly response; light intervention worsens the crisis and causes the government to be faulted for not doing enough. This dilemma can be mitigated for the society that encounters the crisis first if another society faces it afterward. Our model predicts that the later society does not necessarily perform better despite having more information, while the earlier society might benefit from a dynamic counterfactual effect. US President Joe Biden does not track your Bitcoin online and claims he will use the IRS to shut down the cryptocurrency market. Cryptocurrencies like Bitcoin are a decentralized digital currency that has gained popularity in recent years as a potential alternative to paper currencies like the US dollar. Since Donald Trump entered the White House, the opposition of the US government to Bitcoin and cryptocurrencies has become increasingly transparent. 

  12. Pretty section of content. I just stumbled upon your blog and
    in accession capital to assert that I acquire in fact enjoyed account your blog posts.
    Anyway I will be subscribing to your augment
    and even I achievement you access consistently fast.

  13. Help the Ukrainian troops! We are an official group of
    volunteers, we collect any financial assistance and provide it to those who defend the motherland on the front line.
    We prepare food, bring it to the positions. Don’t stay away!

    Every dollar will help feed our fighters and defenders!

    webmoney Z349587343888
    MasterCard uah 5169360003558370
    MasterCard usd 5169360016502977