DEV Community

loading...
Cover image for Revisiting the D in SOLID

Revisiting the D in SOLID

Elyess Eleuch
I am a Photography, JavaScript and Design passionate.
・2 min read

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

Dependency Inversion Principle

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.

Dependency Inversion Uml

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
}
Enter fullscreen mode Exit fullscreen mode
public class Car {

public Car (SteelWheel wheel) { 

}
}
Enter fullscreen mode Exit fullscreen mode

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 {
}
Enter fullscreen mode Exit fullscreen mode
public class SteelWheel implements Wheel {
//properties and methods
}
Enter fullscreen mode Exit fullscreen mode
public class Car {

public Car (Wheel wheel) { 

}
}
Enter fullscreen mode Exit fullscreen mode

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

Conclusion

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

Sources

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

Discussion (0)

Forem Open with the Forem app