Dependency Inversion Principle in C++
Writing Maintainable, Reusable, and Extendable Code
When designing code structure in a high-level language such as C++, it is very important to think about factors such as maintainability and reusability of your code. Software developers are nowadays constantly bombarded with new requirements, platforms and changing library versions. A well-designed software should be able to deal with that. Badly designed (and maintained) software tends toward spaghetti code with dependencies all over the place.
Developers often rely on design patterns and design principles to help them design software. Design patterns are tried and proven recipes for common situations. On the other hand, design principles are guidelines for good system design. While design patterns often apply to a specific language or at least a paradigm (such as object-oriented programming), principles tend to be more general.
The Dependency Inversion Principle (DIP) is one of the SOLID design principles. It states:
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.
High-level modules generally refer to more abstract and complex operations in your code. These operations require one or more low-level modules to perform their function. The straightforward way to implement such complex functionality therefore is to make the high-level modules depend on low-level modules.
Straightforward Implementation
Let’s have a look at an example of a straightforward implementation using two classes in a hypothetical RPG, Player and Door. The desired functionality is to open or close the door once the player interacts with it (depending on its state). The player class may look as follows: