Thursday, 9 July 2020

SOLID Design Principles in C# - Dependency Inversion Principle (DIP)


Definition of the Dependency Inversion Principle?

High-level modules should not depend on low-level modules. Both should depend on the abstraction.
Abstractions should not depend on details. Details should depend on abstractions.

What is high-level module?

A high-level module is a module which depends on other modules.
Ex: Direct Dependency - A concrete class depends on other concrete classes.

What is low-level module?

A low-level module is a module which depends on abstraction (abstract classes/interfaces).
Ex: Inverted Dependency - Concrete class depends only on abstract class or interfaces.

Lets consider a banking transaction scenario where we provide the feature of fetching transcation between the given dates.


  
In the above code both Account and TransactionService are concrete classes and Account class is high-level class which is depending on the low-level module TransactionService. Account  class is having strong tightly coupled dependency with TransactionService. Testing frameworks configuration and code maintenance is typical. Let's refactor the code by adding the Dependency Inversion Principle rules on the above code.

First let's introduce a new interface which acts as a bridge between Account and TransactionService classes. 


Implement the interface in TransactionService class

Finally use the ITransactionService in Account class

Here now the Account class is depending on the ITransactionService which is an abstraction for both Account and TransactionService.  

Advantages:

- It breaks the tight coupling by introducing the abstraction.
- Code maintenance is easier as we are stabling the modules.
- Test Driven Development is easier with the testing frameworks.
- Code-Re-usability.
- Reduces the risk.

No comments: