Dependency Inversion Principle

Prashant Jha
3 min readMar 30, 2023

--

This is last blog on SOLID design principle series. In this blog I’ll write about Dependency inversion principle. For dependency inversion principle, Uncle Bob AKA Robert C. Martin says, “Component should depend upon abstractions, not on concrete details.” Which essentially means:-

  1. High level modules should not depend on low level modules. Both should depend on abstraction.
  2. Abstraction should not depend on details. Details should depend on abstraction.

In order to understand it better, let’s go through an example. Suppose we are building an online store and using stripe as payment gateway.

Later on, we discovered that there is another payment gateway let’s say paypal which is providing better services. So now we want to integrate paypal in our application instead of stripe.

In this current code, to add paypal we have to edit our main component that is App.js. But it is violating dependency inversion principle. According to dependency inversion principle, App.js should be flexible enough to adapt the changes of payment gateway. We can adit the abstract component which is wrapping the payment gateway, but we must not change App.js which is higher order module.

So, to follow the dependency inversion principle, we can modify our code in below way:-

High Level Module
PayPal Payment Gateway
Stripe Payment Gateway
Abstract Component for payment gateway

In this method, we don’t have to do any change in App.js component. Which is high level module. Instead of that we can change PaymentGateway abstract component and same change will be reflected in App.js component.

By this way, here we are following dependency inversion principle. Here high level module, App.js, doesn’t depend on low level module which is Stripe.js and PayPal.js directly. We created another abstract component PaymentGateway to add dynamic change in App.js.

This concludes Dependency Inversion Principle. ‘D’ in SOLID.

--

--

Prashant Jha
Prashant Jha

Written by Prashant Jha

interested in Code, Books, Philosophy, Poems

No responses yet