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:
- public class OrderRepository
- {
- public void Add()
- {
- //Add Order
- }
- }
- public class OrderService
- {
- private readonly OrderRepository _orderRepository;
- public OrderService()
- {
- _orderRepository = new OrderRepository();
- }
- public void CreateOrder()
- {
- _orderRepository.Add();
- }
- }
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:
- public interface IOrderRepository
- {
- void Add();
- }
- public class OrderRepository :IOrderRepository
- {
- public void Add()
- {
- throw new NotImplementedException();
- }
- }
- public class OrderService
- {
- private readonly IOrderRepository _orderRepository;
- public OrderService(IOrderRepository orderRepository)
- {
- _orderRepository = orderRepository;
- }
- public void CreateOrder()
- {
- _orderRepository.Add();
- }
- }
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
- http://www.codeproject.com/Articles/495019/Dependency-Inversion-Principle-and-the-Dependency
- http://lostechies.com/derickbailey/2011/09/22/dependency-injection-is-not-the-same-as-the-dependency-inversion-principle/