The D in SOLID Principles

Dependency Inversion is the last of the SOLID Principles introduced by Bob Martin.

In his original description he outlined two principles 👨🏽‍🏫:

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

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

These two principles enforce the use of abstractions mainly “interfaces” to ensure loose coupling between different levels of modules in object oriented programming.

For example, a simple customer management application in ASP.NET Core would usually have a Repository or Data Access Layer where concrete implementations of how the database is persisted sits.

In this case, the Dependency Inversion Principle expects that concrete implementation that read or write to an I/O device should not be made in your controller.

Let’s jump ahead to apply this in code. 👨🏽‍💻👨🏽‍💻👨🏽‍💻👨🏽‍💻👨🏽‍💻👨🏽‍💻

For this scenario, we will apply dependency inversion in the simplest of ways:

👍Principle A — High level modules should not depend upon low level modules. Both should depend upon abstractions.

i. Create an interface that defines the methods that you will like to implement.

ii. Determine the signature (return type and the parameter) of your methods here. See signature in bold text.

public interface ICustomerRepository
{
    List<Customer> GetAllCustomers();
    Customer GetCustomer(int id);
}

👍Principle B — Abstractions should not depend upon details. Details should depend upon abstractions.

Implement the methods in the lower level module/class with your interface in mind. You must use the signatures(return type and the parameter) specified in your interface to follow Principle B

public class CustomerRepository()
{
    public List<Customer> GetAllCustomers()
  {
     //implementation to retrieve customers from I/O: file, db e.t.c
  }    public Customer GetCustomer(int id)
  {
    //implementation to retrieve customer from I/O: file, db…  e.t.c
  }
}

Simple to apply right ? 👏😀

We have successfully applied Dependency Inversion in a very simple but effective way and can go ahead to supply objects (‘dependencies’) to a class by way of the Dependency Injection Design Pattern as explained in my previous story: https://medium.com/@osewa.dare/hello-dependency-injection-c2b5fb3dd2a8

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top