Dependency Inversion of SOLID principle

As you know, Dependency Inversion Principle is the last principle of SOLID. I talked about SOLID principle and fundamental in my previous post that was about SRP. Now I'm gonna to consider the dependency inversion of SOLID. Based on definition "High level modules should not depend upon low level module, both should be depend upon abstraction". Or in other definition "abstraction should not depend upon details, details should depend upon abstraction". When you have relationship between you classes in OPP, that relationship should be stated on terms of abstraction rather than concrete implementation. "The benefits of using loose coupling aren’t always instantly evident, but they become visible over time, as the complexity of a code grows." in concrete implementaion changes to one class will break the other class.

Take a look at this implementation:

  1.    public class OrderRepository
  2.     {
  3.         public void Add()
  4.         {
  5.             //Add Order
  6.         }
  7.      }
  9.     public class OrderService
  10.     {
  11.         private readonly  OrderRepository _orderRepository;
  13.         public OrderService()
  14.         {
  15.             _orderRepository = new OrderRepository();
  16.         }
  18.         public void CreateOrder()
  19.         {
  20.             _orderRepository.Add();
  21.         }
  22.      }


I just create an instance of the OrderRepository inside the OrderService to use the add method. As you know every changes in OrderRepository will destroy the OrderService class and we should modify the OrderService class every times. Now notice about this implementation:


  1.     public interface  IOrderRepository
  2.     {
  3.         void Add();
  4.     }
  6.     public class OrderRepository :IOrderRepository
  7.     {
  8.         public void Add()
  9.         {
  10.             throw new NotImplementedException();
  11.         }
  12.     }
  14.    public class OrderService
  15.     {
  16.         private readonly IOrderRepository _orderRepository;
  18.         public OrderService(IOrderRepository orderRepository)
  19.         {
  20.             _orderRepository = orderRepository;
  21.         }
  23.         public void CreateOrder()
  24.         {
  25.             _orderRepository.Add();
  26.         }
  27.     }


I just added an interface, but if you take a deeper look at OrderService,it doesn't have any concrete instantiating of OrderRepository and every change in IOrderRepository should be implemented in OrderRepository and OrderService just talks to IOrderService. (Don't call use we'll call you!). I also used constructor injection that you can read more about that here.


You can read more about DIP


Tags: Design Pattern C# Principle

comments powered by Disqus