{{announcement.body}}
{{announcement.title}}

Dependency Inversion Principle in C++: SOLID as a Rock

DZone 's Guide to

Dependency Inversion Principle in C++: SOLID as a Rock

High-level modules should not depend on low-level modules. Both should depend on abstractions. Abstractions should not depend on details. Details should depend on abstractions.

· Web Dev Zone ·
Free Resource

Dependency Inversion Principle(in C++) is the fifth and last design principle of a series SOLID as a Rock design principles. The SOLID design principles focus on developing software that is easy to maintainable, reusable, and extendable. In this article, we will see an example code with the flow and correct it with help of DIP. We will also see guidelines and benefits of DIP at the ens of the article.

By the way, If you haven't gone through my previous articles on design principles, then check out the following quick links:

  1.  SRP -- Single Responsibility Principle.
  2.  OCP -- Open/Closed Principle.
  3.  LSP -- Liskov Substitution Principle.
  4.  ISP -- Interface Segregation Principle.
  5.  DIP -- Dependency Inversion Principle.

The code snippets you see throughout this series of articles are simplified not sophisticated. So you often see me not using keywords like override, final, public(while inheritance) just to make code compact and consumable(most of the time) in single standard screen size. I also prefer struct instead of class just to save line by not writing "public:" sometimes and also miss virtual destructor, constructor, copy constructor, prefix std::, deleting dynamic memory, intentionally. I also consider myself a pragmatic person who wants to convey an idea in the simplest way possible rather than the standard way or using Jargons.

Note:

  • If you stumbled here directly, then I would suggest you go through What is design pattern? first, even if it is trivial. I believe it will encourage you to explore more on this topic.
  • All of this code you encounter in this series of articles are compiled using C++20 (though I have used Modern C++ features up to C++17 in most cases). So if you don't have access to the latest compiler you can use https://wandbox.org/, which has preinstalled boost library as well.

Intent

=> High-level modules should not depend on low-level modules. Both should depend on abstractions.
=> Abstractions should not depend on details. Details should depend on abstractions.

  • Above lines might seem cryptic at first but don't stick here keep going. You will get it by example.

What are the High-level & Low-level modules?

=> High-level modules: describes operations which are more abstract in nature and contain more complex logic. These modules orchestrate low-level modules in our application.
=> Low-level modules: describes implementations that are more specific and individual to components focusing on details and smaller parts of the application. These modules are used inside the high-level modules.

Violating Dependency Inversion Principle

C++
  • When later on the container of Relationships changes from vector to set or any other container, you need to change in many places which isn't a very good design. Even if just the name of data member i.e. Relationships::m_relations changes, you will find yourself breaking other parts of code.
  •  As you can see Low-level module i.e. Relationships directly depend on High-level module i.e. Research which is essentially a violation of DIP.

Dependency Inversion Principle Example

  • Rather, we should create an abstraction and bind Low-level and High-level modules to that abstraction. Consider the following fix:
C++
  • Now, no matter the name of container or container itself, changes in Low-level modules, High-level modules, or other parts of code, which followed DIP, will remain intact.
  • The Dependency Inversion Principle (DIP) suggests that the most flexible systems are those in which source code dependencies refer only to abstractions, not to concretions.
  • This is the reason why most experienced dev uses STL or library functions along with generic containers. Even using an auto keyword at appropriate places may help in creating generic behavior with less fragile code.
  • There are many ways you can implement DIP, as long as C++ concerns most people use static polymorphism (i.e. CRTP unless they need a dynamic one), template specialization, Adapter Design Pattern, type-erasure, etc.

Yardstick to Craft Dependency Inversion Principle(DIP) Friendly Software

  • If you find enforcing DIP difficult, then just design abstraction first and implement your high-level module on the bases of abstraction without having any knowledge of the low-level module or its implementation. Because of this process, DIP is also known as Coding To Interface.
  • Keep in mind that all Low-level-modules/subclasses adhere to the Liskov Substitution Principle. This is because the Low-level-modules/subclasses will be used via the abstract interface, not the concrete classes interface.

Benefits

      => Reusability

  • Effectively, the DIP reduces coupling between different pieces of code. Thus we get reusable code.

      => Maintainability

  • It is also important to mention that changing already implemented modules is risky. By depending on abstraction and not on concrete implementation, we can reduce that risk by not having to change high-level modules in our project.
  • Finally, DIP when applied correctly gives us flexibility and stability at the level of the entire architecture of our application. Our application will be able to evolve more securely and become stable & robust.

Conclusion

As you can see we took a basic example of code & converted it into a reusable, flexible & modular piece of code. If I would have to summarize DIP in simple & short sentence then it would be like:

Do not use the concrete object directly unless you have a strong reason to do so. Use abstraction instead.

DIP trains us to think about classes in terms of behavior, rather than construction or implementation.

Have Any Suggestions, Query or Wants to Say Hi? Take the Pressure Off, You Are Just a Click Away.

Topics:
c++, coding basics, cpp, design pattens, design principles

Published at DZone with permission of Vishal Chovatiya . See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}