Skip to main content

SOLID - Dependency Inversion - Principle


Usually you instantiate dependencies of a class inside that class. In the process, the class becomes tightly coupled with its dependencies. Any change in the dependency may require a change in the class. The root cause of this tight coupling is that the class creates its own dependencies. To loosen this coupling, dependencies can be supplied to a class from the external world. That’s where the Dependency Inversion Principle comes into the picture. The DIP can be stated as the following

A. High-level classes should not dependent on low-level classes. Both of them should depend on abstractions.
B. Abstractions should not depend upon details. Details should depend upon abstractions.

Assumptions
Assuming we had completed the Interface Segregation example in our SOLID Principle. We may now trying to make an example of Dependency Inversion

The Requirement
There is a requirement stated that we need to log all the message that being sent from all micro services.

The Code - IMicroServicesLogger
First we create an interface
Next Create Dependency Inversion In Client Classes
In this case we will make use of InternalMessageChannel and ExternalMessageChannel to demonstrate Dependency Inversion. In the code snippet below, we first insert a constructor to accept the IMicroServicesLogger. We also leave the default constructor just in case there is no need for logging during development phase. Next we perform the Logging during the specific action method.
The Implementation Of Logger
Next we may implement it on a logger, Assuming we have a specific logging mechanism for Accounting Module, we may then implement the interface something like this.
The Client Implementation
Next we may make use of the logger with Dependency Inversion Technique.
Conclusion
From the article, we may understand how to perform SOLID in our design patterns. It is important to understand how Dependency Inversion really help us in designing a maintainable/readable software codes.

Published on : 10-Jan-2019
Ref no : DTC-WPUB-000105

About Author

My photo
Wan Mohd Adzha CAPM,MCPD,MCSD,MCSE
Passionate about new technology ( Software Engineering ) and how to build,manage and maintain them

Comments