DIP - Dependency Inversion Principle

Depend only on abstractions rather than on concretions.

Dependency Inversion Principle is the last principle of SOLID design principles. Here, I quote directly from the source (Uncle Bob), as it is beautifully written:

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

Basically, this means that your code should never depend on the implementation, but it should only depend on the interfaces (or abstract classes).

This will enable you to change or replace any implementation with just another implementation, and none of the client code needs to change or worry about it since it only depends on the interfaces.

Here, I first give you a bad example that violates the DIP:

    public class OrderProcessor : IOrderProcessor 
{
public void Process(IOrder order)
{
//Perform validations..
if (new OrderRepository().Save(order))
new OrderNotifier().Notify(order);
}
}

This is bad example because the OrderProcessor class depends upon the actual implementation of OrderRepository and OrderNotifier. The client code will need to change if, say, we need to have a different repository persistence layer tomorrow or we need a different notification mechanism than SMS or e-mail.

Now we provide you with the good example by correcting the bad one:

    public class OrderProcessor : IOrderProcessor 
{
private readonly IOrderRepository _orderRepository;
private readonly IOrderNotifier _orderNotifier;

public OrderProcessor(IOrderRepository orderRepository,
IOrderNotifier orderNotifier)
{
_orderRepository = orderRepository;
_orderNotifier = orderNotifier;
}

public void Process(IOrder order)
{
//Perform validations..
if (_orderRepository.Save(order))
_orderNotifier.Notify(order);
}
}

With these changes, our OrderProcessor class does not have dependencies on the actual implementations anymore; instead, it only relies on the interfaces--IOrderRepository and IOrderNotifier. Now if we want to change the way notifications are sent, we will need to have a new implementation of IOrderNotifier and pass that implementation to OrderProcessor without any code changes to the OrderProcessor class.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.27.171