A Guide to Loose Coupling and Writing Better Python Code With Dependency Inversion
Dive into the popular design pattern
This post is part 5 of a series on the SOLID principles. You can find post 4 here, post 3 here, post 2 here and post 1 here.
We have finally reached the last of the SOLID principles. As usual, we start with a definition:
Principle 5 is named the dependency inversion principle. The definition has two parts:
A. High-level modules should not import anything from low-level modules. Both should depend on abstractions (e.g., interfaces).
B. Abstractions should not depend on details. Details (concrete implementations) should depend on abstractions.
In traditional software architecture we design lower level components to be used/consumed by higher level components. In other words, higher level components depend on lower level components. This dependency causes tight coupling in the software. As explained in principle one, we strive to achieve loose coupling to make it easier to develop, maintain and change code in the future.
The dependency inversion principle inverts this dependency in the sense that instead of higher level components depending on lower level ones, both should depend on abstractions. This abstraction layer would be an intermediate component that sits between the higher and lower level components. The two will then use this component to communicate and interact amongst each other. The abstraction component would usually be implemented as an interface.
Time for some code and a concrete example!
Code
Consider the following example where we model a robot:








