Close
Dependency Inversion Principle

Software Design S.O.L.I.D principles guide book – Dependency Inversion Principle

Introduction

Continuing our discussion on S.O.L.I.D principle, checkout Open Closed Principle (OCP), Liskov Substitution Principle (LSP) if not so far. In this blog lets cover yet another principle i.e. Dependency Inversion Principle short hand DIP. Lets dive in

Dependency Inversion Principle

Dependency Inversion Principle states

High level modules should not depend on concrete implementation of low level modules, rather they should depend on abstract classes or interfaces.

Lets try to understand this statement, why anyone don’t want the high level module to depend on a low level module concrete implementation? The reason is very simple, low lowel modules are very volatile in nature i.e. changes are very frequent due constant updation in requirements. To really incorporate these requirements, it would be difficult if the dependency is regit.

If not the concrete implementation then abstract class / interfaces but why? Again the reason is simple abstract class/ interfaces tend to change very infrequently that the low level modules implementation, it does make sense for the high level module to depend on the Abstract class/ interface.

Okay, all this is fine. But why should we call it dependency inversion? If you see the high level module depends on the abstraction layer, whereas the modules that contain the actual implementation there dependency is inverted towards the abstract layer as well. That why!

quote from Robert C. Martin, which dipicts the relation between OCP & DIP

If OCP states the Object Oriented design goal, then DIP states the primary mechanism to achieve it

Let’s take a real world example that is well known the Android OS. It appears that Android as a single entity but beneath it has a lot of abstract. One example is how Android interacts with different hardware subsystems like gps, audio, and video. But how it does it is via an abstraction IPC layer AIDL(Android Interface definition language) it does not depend on the lower layer hardware system system implementation rather depends on Abstraction. Because if you see Android can run on any chipset SOC vendor. Now you know how they do it, this in a way shows inverting the dependency makes the flexible design.

Dependency Inversion principle illustration siting Android Framework

Conclusion

In this blog we discussed DIP, in summary the high level system should only focus on high level policies, rather than depending on the concrete dependencies. Hope you will take care of this in upcoming projects! In the next blog I will discuss yet another S.O.L.I.D principles.