What is Dependency Inversion Principle (DIP)?

Sahil Sanjeev Gathani
3 min readNov 14, 2020

--

Introduction

The dependency inversion principle is one of the five SOLID principles of object-oriented design. It states:

High-level modules should not depend upon low level-modules. Both should depend upon abstractions.

Abstractions should not depend upon details. Details should depend upon abstractions.

Without worrying too much about the definition, we can visualize how DIP works through an example.

Example

For example, consider the UML class diagram shown below. In the diagram, the higher-level House has a dependency with LivingRoom through the addLivingRoom() method.

UML class diagram for House and LivingRoom

Now suppose we want to add another room in this house called StudyRoom. One option would be to add another method in House, such as addStudyRoom() and create a new class StudyRoom. This suggestion is sketched out in the UML class diagram below.

UML class diagram for House, LivingRoom and StudyRoom

However, this would be a clear violation of the Open-Close Principle (SOLID) because the internal code of House needs to be modified to accommodate this change. Note that in this case the high-level House class does indeed depend on the lower-level LivingRoom and StudyRoom classes, which is precisely what DIP warns us to avoid.

So, how can we fix this? As the DIP hints, we can add an abstraction through an interface to bridge the dependency between House and LivingRoom. A potential solution is shown the UML class diagram below.

UML class diagram for House, Room, LivingRoom and StudyRoom

By applying the DIP, we notice that the higher-level House class no longer depends on specific lower-level classes such as LivingRoom, but instead depends on an intermediary interface Room. In other words, communication between the two tiers of classes (details) is not defined by the internal workings of these classes, but rather their communication (and therefore internal workings) is governed based on their intermediary interfaces (abstractions).

Also note how the House class need not be modified unlike the previous implementation. In the future, adding a new room simply requires the room to implement the Room interface which is still compatible with House.

Pros & Cons

As demonstrated clearly in the example above, one benefit of applying the DIP is the decoupling of higher-level and lower-level classes. Thus, changes to low-level classes does not necessitate any changes for high-level classes. However, one immediate drawback is the addition of more classes (Room interface in the previous example). Depending on the exact situation as well as the certainty for future extension or modification, it may not be necessary to blindly apply this principle in all scenarios.

--

--