SOLID : Dependency Inversion Principle

I started of this segment called Design Patterns and Principles long back, but I somehow missed DIP of Solid Principles. It is high time I add the missing piece.

Dependency Inversion Principle (DIP) states that a high level modules should not depend on low level modules and both should depend on abstraction. Further more, abstractions should not depend on details, rather details should depend on abstractions.

Consider the following code.

public class ShoppingCart
{
    public PayPalPaymentProcessor _paypalPaymentProcessor = new PayPalPaymentProcessor();

    public void ProcessPayment(decimal amount)
    {
        _paypalPaymentProcessor.Process(amount);
    }
}

public class PayPalPaymentProcessor
{
    public void Process(decimal amount)
    {
        // Implementation
    }
}

This is a classical violation of Dependency Inversion Principle. The high level module depend on the low level implementation details of PayPalProcessor. Consider in future, you would need to switch from PayPal to another provider. This would require you to modify the Shopping Cart, thereby violating Open Closed Principle.

What should instead be done is that the high level module, in this case, the ShoppingCart should depend on abstractions. Let us introduce an interface IPaymentProcessor.


public interface IPaymentProcessor
{
    void ProcessPayment(decimal amount);
}

public class PaypalPaymentProcessor : IPaymentProcessor
{
    // details
}

As you can now see, we have introduced IPaymentProcessor interface and implemented the behavior in PaypalPaymentProcessor class. Now we can replace the tightly coupled implementation of payment processor in the high level module with the interface/abstraction.

public class ShoppingCart
{
    public IPaymentProcessor _paypalPaymentProcessor;

    public ShoppingCart(IPaymentProcessor paymentProcessor)
    {
        _paymentPaymentProcessor = paymentProcessor;
    }

}

Now, you can observe the high level module does not depend on low level module, but rather on abstraction. Furthermore, if you inspect the interface, it does not describe the details (paypal/any other provider). The abstraction does not care about the details.

That’s it for the Dependency Inversion Principle.

Leave a comment