SOLID principle – DIP

This article will introduce one of solid principles DIP which is the abbreviation of Dependency Inversion Principle.

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

Interpretation: Use abstraction rather than concrete object 

Example:

Say you go to a restaurant for a dinner, you order a shrimp-fried rice(concrete object) to a waiter, but the waiter tells you that shrimp-fried rice has already sold out and you have to choose something else. To prevent from these kinds of scenario, you should choose something else for your dinner(abstraction). You then get more choices.

Code Sample:

In C#, we can use Unity library as IOC Container to fulfill the spirit of DIP principle.

IOC: This stands for Inversion Of Control which is responsible for the construction of object(done by Unity).

DI: this stands for Dependency Injection which is a way to achieve IOC

Create interface

Implement two interfaces (beef noodle and shrimp fried rice)

shrimp fried rice

Beef noodle

Main console

The result

Conclusion

DIP is a main way to achieve loose coupling. For instance if you use a concrete object for unit test, you then have to write a unit test for every related object. If you use DIP and unity library instead, you don’t have to do this and this improves code maintenance.