Revisiting the D in SOLID

Photo by Pavel Nekoranec on Unsplash
This is a continuation of the SOLID. In the last post, I covered the I and now we will be continuing with the last D. So if you didn’t check the last post, feel free to click on the link: https://dev.to/sightlessdog/revisiting-the-s-in-solid-adg

The Dependency Inversion Principle is based on the Open/Closed Principle and the Liskov Substitution Principle. And it basically states that high-level modules shouldn’t depend on low-level modules.
Simply put, never depend on anything concrete, only depend on abstractions, which never depend on details but the other way round, details depend on abstractions.

As you see in the picture, inversion doesn’t mean that the low-level module now depends on the higher-level one. Because in conventional application architecture, low-level components are designed to be consumed by the higher-level components.

time for a simple example, right?

public class SteelWheel {
//properties and methods
}
public class Car {

public Car (SteelWheel wheel) {

}
}

As we can see our car class is forced to depend on a concrete implementation of wheel. And what does our principle say?

Never depend on anything concrete, only depend on abstractions
We did violate our principle, right?

Well, you may be wondering right now, oh, the car class looks good, why should I care this much?.
Mmmm, good question, but imagine this with me. You would want one day to change your SteelWheels to AlloyWheels. What would you do the car class?
I hope that you are getting my point, if you change later the car class, you would violate the open/closed principle.
The car class shouldn’t care about the wheel being used.

public interface Wheel {
}
public class SteelWheel implements Wheel {
//properties and methods
}
public class Car {

public Car (Wheel wheel) {

}
}

And that’s how the low-level module and the high-level one depend on the abstraction.

I hope that this series was helpful. Wish you a good day!

https://en.wikipedia.org/wiki/Dependency_inversion_principle
Robert C. Martin “Principles of OOD”
Meyer, B. (1997): Object-Oriented Software Construction, 2nd edition
http://www.cvc.uab.es/shared/teach/a21291/temes/object_oriented_design/materials_adicionals/principles_and_patterns.pdf

Originally published at https://dev.to on February 7, 2021.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store