Dependency Inversion Principle: SOLID Design Principles

Share the Article

What is Dependency Inversion Principle

Dependency Inversion principle is one of the most important principle for object oriented application designing. It is also contributing fifth letter “D” in SOLID acronym where D stand for Dependency Inversion. This principle addresses future modifiability and maintainability issues of an application. Main idea of this principle is to introduce loose coupling between the classes inside an application so that future enhancement is very easy.

“Dependency Inversion” principle try to design classes such that high level classes should not depend on low-level classes directly. If high-level modules become directly dependent on lower-level modules then replacement of lower-level module becomes very difficult . If any updates in lower level we need to update high level also . Due to this class maintainability will be very tough and time consuming. Plus, testability will also impact. For each change in low-level part, we need to update test cases for high-level parts also.

We should design high-level module and low-level module such that they should not directly interact with each other. Instead of this, we should have an abstraction layer, which take care of interaction. Interaction between level should depend on abstraction layer, so that we can very easily replace low layer module.

How

Lets us understand the need of “Dependency inversion” principle by taking an example of application of School.

When not using Dependency Inversion Principle

Below application is depicting class School where we are setting games and number of player needed for a game .Finally, we are showing details about all the games present in a School.

#include<iostream> #include<map> #include<string> using namespace std; class Cricket { int m_player; public: Cricket(int player) { m_player = player; } int getPlayer() { return m_player; } }; class Badminton { int m_player; public: Badminton(int player) { m_player = player; } int getPlayer() { return m_player; } }; class School { map<string,int> m_game; public: void addCricket(Cricket &c1) { int t = c1.getPlayer(); m_game.insert (std::pair<string,int> ("Cricket",t)); } void addBadminton(Badminton &b1) { int t = b1.getPlayer(); m_game.insert(std::pair<string,int> ("Badminton",t)); } void showAllGame() { auto it = m_game.begin(); while(it!=m_game.end()) { cout<<it->first<< " " <<it->second<<endl; it++; } } }; int main() { School a1; Cricket c1(12); Badminton b1(2); a1.addCricket(c1); a1.addBadminton(b1); a1.showAllGame(); return 0; }

As seen above, we are supporting Cricket and Badminton games .

Below are the details of application:

  • School is the high-level module.
  • Cricket and Badminton are low-level modules.
  • School is directly interacting with Cricket and Badminton

Suppose, now we have to update above application for future need as More games such as Hockey, Swimming are introduced.

Below is the updated design of above application:

class School { map<string,int> m_game; public: void addCricket(Cricket &c1) { int t = c1.getPlayer(); m_game.insert(std::pair<string,int> ("Cricket",t)); } void addBadminton(Badminton &b1) { int t = b1.getPlayer(); m_game.insert(std::pair<string,int> ("Badminton",t)); } void addHockey (Hockey h1) { } void showAllGame() { auto it = m_game.begin(); while(it!=m_game.end()) { cout<<it->first<< " " <<it->second<<endl; it++; } } };

As seen above, high-level class School is very tightly coupled with low level classes. Therefore, any update is directly impacting School class.

We are violating “Dependency Inversion” principle. As per “Dependency Inversion” we should have very loose coupling between layers. Hence, we are seeing side-effects also due to violation of “Dependency Inversion” in terms of maintainability efforts.

How

Let’s update above School with “Dependency Inversion” principle.

Thumb rule – High-level should not directly interact with low-level and we should have abstraction between them.

First create abstract class for Low-Level Classes

First create abstract class Game for and Cricket and Badminton. This class shall reside in School class.

class Game { }; class Cricket: public Game { }; class Badminton: public Game { }; Class School { Game g1; };

Create relevant methods in abstract class

Basically, we require loose coupling between high and low level. Hence create appropriate interface for interacting between all layers.

class Game { public: void showGames(); }; class Cricket: public Game { }; class Badminton: public Game { }; Class School { Game g1; public: void showGames() { gl.showGames(); } };

Below is the class diagram:

Dependency inversion principle UML diagram. SOLID design principles

Same example now using Dependency Inversion Principle

Below is the updated application:

#include<iostream> #include<map> #include<string> using namespace std; class Game { static map<string,int> m_game; public: void showGames() { auto it = m_game.begin(); while(it != m_game.end()) { cout<<it->first<< " " <<it->second<<endl; it++; } } }; map<string,int> Game::m_game; class Cricket: public Game { int m_player; public: Cricket(int player) { m_player = player; Game::m_game.insert(std::pair<string,int> ("Cricket",m_player)); } int getPlayer() { return m_player; } }; class Badminton: public Game { int m_player; public: Badminton(int player) { m_player = player; Game::m_game.insert(std::pair<string,int> ("Badminton",m_player)); } int getPlayer() { return m_player; } }; class School { Game m_g; public: void showAllGame() { m_g.showGames(); } }; int main() { School a1; Cricket c1(12); Badminton b1(2); a1.showAllGame(); return 0; }

As seen above, now we have abstraction layer “Game” between high-level School and low-level Cricket and Badminton modules. In future, if we have to add more features or new games then we just need to update abstraction layer. Finally, if we have to add new game, just derive a new class from Game class. No change in School class.

Pros & Cons of Dependency Inversion Principle

Pros

  • Future addition of module is very easy due to loose coupling
  • Changes are very less so less impact on Unit test

Cons

  • Complex due to addition of one more abstraction layer

Main Funda: Dependency Inversion Principle ensures that there is loose-coupling between different logical levels.

Advanced C++ Topics

Single Responsibility Principle
Open Closed Principle
Liskov’s Substitution Principle
Interface Segregation Principle

Share the Article

4,701 thoughts on “Dependency Inversion Principle: SOLID Design Principles

  1. Older enquiry estimates that about 70 percent of men ages 70 and older dispatch being “now adept” or “under no circumstances able” to accomplish an erection not at all bad for the benefit of good enough intercourse, compared with simply 30 percent of older men who report being “usually superior” or “each or approximately each time able.” Source: sanofi cialis

  2. Pingback: 2features
  3. While it was unclear from the record what type of medical documentation was allegedly compromised, the EEOC s regulations specifically provide for the confidentiality of medical records, and Complainant stated a claim of breach of confidentiality under the Rehabilitation Act s confidentiality requirement viagra for men side effects

  4. How do I attract my husband
    Erectile dysfunction is one of the men’s sexual health disorders. It is cognized as an ineptness of men to attain erection during procreant communication even if they are sexually excited. Other symptoms of ED are, either it remains after a transitory while or does not occur at all. It is a repeated process. Erectile dysfunction is also called a model of impotence. Frailty is a encyclopaedic side and covers many other men’s fettle sex disorders like- too early ejaculation, lack of lustful desire, etc. Erectile dysfunction does not contain these problems. All these problems interdependent to Erectile dysfunction can be cured with the daily help of blue viagra pills and other viagra over the counter europe medicines.

    Causes
    Erectile dysfunction does not have any specific cause. There are multifarious reasons behind its occurrence. It can be- true reasons, your form problems, medicines you are entrancing, nervous reasons, etc. Give permission’s enjoy a look on ED causes in particular. Erectile dysfunction causes are- momentous blood stress, diabetes, high blood cholesterol, anxiety diseases (Parkinson’s disability and multiple sclerosis), surgery, smutty hormone levels, lifestyle factors (smoking and drinking) and others (force, concern, tenseness, misgivings, cavity). Aging factors also outstrip to ED, but aging in itself is not a cause. Low testosterone levels also in some cases command to erectile dysfunction. Side effects caused by medications also establish men unqualified in compensation erection.

    But there is nothing to harry about as treatments are to hand with a view ED. A specific such present treatment as regards ED is can you buy viagra in mexico over the counter.

  5. It was in fact concluded that if five such transporters contributed randomly they could account for the flux of the most permeable drug tested verapamil 35 of the time buy stromectol 12mg Around day 43, free cholesterol values in E16 mice were also higher than in WT 43

  6. I must add that it can take up to ten months before a pregnancy is realized purchase cialis online cheap success alesse side effects Republicans and other critics of Obamacare have cited the jump in part time workers as evidence that employers have been cutting back on hours to avoid higher healthcare costs under Obamacare, which will require businesses with 50 or more full time workers to provide health insurance in 2015

  7. O Bitcoin usa um código complexo, que não pode ser alterado, e todas as transações são protegidas por criptografia. Cada transação é validada por um grupo de pessoas, chamadas de mineradores, por meio de computadores, que gravam estas operações na blockchain, garantindo a segurança de todo o sistema. Continue lendo e descubra como declarar Bitcoin em 2021. Um dos destaques da BitcoinTrade é a isenção de comissões em Bitcoin das negociações realizadas. Outro ponto positivo é a tecnologia de segurança, que atingiu a certificação PCI DSS Nível 2 para a criptografia dos dados de cartão de crédito nos pagamentos. A exchange com maior volume anual foi a Binance, com 122.046 BTC negociados, correspondendo a 29,8% do mercado nacional. Em segundo lugar, operando 54.016 bitcoins, o Mercado Bitcoin, e ,na sequência, a NovaDax, com 50.513 BTC. https://uprahp.com/community/profile/arlieluisini531/ PI NETWORK DEFI caiu 72.6 % nos últimos três meses e, com sua pequena capitalização de mercado, é muito provável que esse movimento de preços continue. No entanto três meses ainda é considerado cedo no mundo cripto e também é provável que PI NETWORK DEFI ‘s preço pode saltar para trás se ele tem uma equipe sólida e entregou o que prometeu em seus papéis brancos. Portanto, os comerciantes devem ser cuidadosos e pesquisar exaustivamente para ver se a PI NETWORK DEFI é apoiada por uma equipe de desenvolvimento sólida e se PI NETWORK DEFI tem potencial para crescer. Ascriptomoedasestão surfando um momento de alta, com os ativos caindo cada vez mais no gosto dos investidores. A moeda mais tradicional do setor, obitcoin, já subiu 91% no acumulado do ano.

  8. Zhang Z, Zhou L, Zhou Y, et al cialis 20 mg POI is associated with menopausal symptoms in women at reproductive age and increased risk of cardiovascular disease and fractures, mainly due to estrogen deficiency

  9. Anyway, the master is rich and a big weapons merchant, Rogge s men are all equipped with heavy shields, spears, battle axes and hand crossbows, At the other end of the castle are two can you take turmeric with blood pressure meds large smelting workshops, and eight towering chimneys are spewing thick black smoke kamagra powered by phpbb

  10. How long can the average man stay erect
    Erectile dysfunction is one of the men’s sexual trim disorders. It is cognized as an unfitness of men to attain erection during sexual intercourse even if they are sexually excited. Other symptoms of ED are, either it remains after a dumpy while or does not come off at all. It is a repeated process. Erectile dysfunction is also called a standard of impotence. Impotence is a widespread off the mark aspect and covers scads other men’s vigour sex disorders like- untimely ejaculation, lack of procreative pine, etc. Erectile dysfunction does not involve these problems. All these problems interdependent to Erectile dysfunction can be cured with the daily help of can you buy real viagra online and other how can i get viagra pills medicines.

    Causes
    Erectile dysfunction does not take any definite cause. There are multifarious reasons behind its occurrence. It can be- physical reasons, your condition problems, medicines you are delightful, heated reasons, etc. Excuse’s deliver a look on ED causes in particular. Erectile dysfunction causes are- momentous blood pressure, diabetes, loaded blood cholesterol, nerve diseases (Parkinson’s disability and multiple sclerosis), surgery, weak hormone levels, lifestyle factors (smoking and drinking) and others (stress, desire, nervousness, dread, bust). Aging factors also prompt to ED, but aging in itself is not a cause. Deficient testosterone levels also in some cases command to erectile dysfunction. Side effects caused by medications also establish men unfit in behalf of erection.

    But there is nothing to agonize about as treatments are on tap for ED. Whole such available treatment representing ED is pill teva 5343 vs viagra.

  11. Critics allege that a number of popular coin-pushing vloggers are in fact operating out of their own homes, using their own coin pushers — without revealing the truth to their audiences. These creators will in turn ask their followers to fund their “gambling” by donating to them on YouTube live streams or by joining their Patreons. Roshtein does not play in one casino for jackpots on YouTube but prefers several at once. What does that tell us about? Well, most likely that he’s not some sort of brand from a casino that’s supposedly being promoted to attract more players to his platform. Instead, his choices are brands with a positive reputation. Therefore, all of the affiliate Roshtein – “with a mark of quality” and without fraud, if it can be put that way. https://wiki-burner.win/index.php?title=Crypto_casino_line Casumo is one of the most distinctive and innovative online casino and sports betting operators in Europe. Our goal has always been to design, improve, reinvent and shape the future of online gaming. The company was founded in Sweden in 2012 and today we are proud to offer our products in a number of highly regulated markets including Sweden, Denmark, the United Kingdom, Germany and other emerging markets worldwide subject to applicable law. Sign in with social networks Casumo is an approved UK gambling operator under licence number 39265. Its online casino game selection consists of 2000+ slots, 25+ roulette games, 15+ blackjack games and 80+ live dealer games, also available on mobile. The welcome bonus for UK players is up to £25 and 20 bonus spins. In other words, Casumo Casino is a great place for UK players.

  12. How can you tell if a man has erectile dysfunction
    Erectile dysfunction is one of the men’s sexy healthfulness disorders. It is cognized as an ineptness of men to attain erection during procreant intercourse to if they are sexually excited. Other symptoms of ED are, either it remains in behalf of a deficient rare while or does not come off at all. It is a repeated process. Erectile dysfunction is also called a type of impotence. Frailty is a wide light and covers innumerable other men’s vigour reproductive disorders like- untimely ejaculation, dearth of lustful give one’s eye-teeth for, etc. Erectile dysfunction does not presuppose implicate these problems. All these problems interdependent to Erectile dysfunction can be cured with the help of chinese herbal viagra pills and other where to buy viagra in singapore medicines.

    Causes
    Erectile dysfunction does not take any definite cause. There are multifarious reasons behind its occurrence. It can be- physical reasons, your healthfulness problems, medicines you are taking, emotional reasons, и так далее Excuse’s have a look on ED causes in particular. Erectile dysfunction causes are- high blood weight, diabetes, favourable blood cholesterol, grit diseases (Parkinson’s disability and multiple sclerosis), surgery, subdued hormone levels, lifestyle factors (smoking and drinking) and others (upset, desire, tension, fear, cavity). Aging factors also prompt to ED, but aging in itself is not a cause. Deficient testosterone levels also in some cases lead to erectile dysfunction. Side effects caused past medications also net men unable to save erection.

    But there is nothing to harry give as treatments are convenient in place of ED. One such convenient treatment proper for ED is cheap viagra mastercard.

  13. You are so awesome! I don’t believe I have read through anything like that before. So great to discover another person with some genuine thoughts on this subject matter. Seriously.. many thanks for starting this up. This site is one thing that is required on the web, someone with some originality.

  14. Sadly, no – not all gambling sites will accept cryptocurrencies. That’s why we’ve put together a list of online casino sites that carry out crypto transactions without any hassle. That is essentially what many did with cryptocurrency: they forgot to sell when they had already won, and if you think $100,000 is a lot to lose, you have not met Brian Armstrong, who lost 3.8 billion dollars in less than three days in some coin I have never heard about. In those conditions, as a public ledger, blockchain networks maintain records of all gaming transactions- payouts, wins, and losses in a both transparent and immutable manner. This process eliminates the risk of fraud and provides legitimacy by displaying the record and transitional history of every user which is inalterable. https://www.nadee-ubon.go.th/community/profile/jaclyncoombs13/ Bitcoin Blackjack Casino Dice If you’re looking for a real casino, try playing Spanish Blackjack at a bitcoin casino. Although Spanish blackjack is based on the classic game of blackjack, the rules are different. In Spanish blackjack, no tens are played, increasing the odds in favour of the dealer. However, various bonuses are available to balance out the advantage. The rules of online blackjack are fixed, while the rules of land-based blackjack may vary from country to country and from casino to casino. Some Bitcoin blackjack sites features a Bitcoin faucet—a reward system often in the form of a website or an app—which “dispenses” satoshis or small amount of bitcoins. Before placing real-money bets, you can use these satoshis in trying the game out. Think of it as playing Bitcoin blackjack in Free Play mode, yet you get the chance to turn these freebies into winnings.