Dependency inversion

Ace Rodstin
2 min readFeb 25, 2023

One of the principles of SOLID is the dependency inversion. There are many resources with a dependency inversion detailed description such as books and the articles. And most of candidates at a job interview successfully answer to the question: “What is the dependency inversion?”. But when real practice takes place the another question arises what is the inversion meaning and how to program it?

Implementation detail dependency

Let’s make a little introduction to the beginning of programming. The first programs, before polymorphism and object-oriented programming was invented, looked like this.

Dependencies was directed in the same direction. But there is a problem and not one.

  1. The Controller depends from implementation detail — calculateFulltimeSalary() and caclculatePartialTimeSalary() methods
  2. It is not difficult to realize, that when adding new worker type will need to edit the Controller
  3. When adding new method once again to the Controller, it grows up very fast and will become a mess

Therefore a program has separated to components, which depends from hardware, data, etc. Hence if a new printer added for example, it is enough to program only driver, while a document creation responsible module still unchanged.

Class abstraction dependency

When object-oriented programing and polymorphism were introduced, it is became possible to hide implementation detail through class interface. That is why one of the most popular resourcehas pointing

High-level modules should not import anything from low-level modules. Both should depend on abstractions (e.g., interfaces).

Which eventually led to the next picture, that illustrates dependencies of classes.

The diagram has also the inversion meaning presentation — at some time the dependency arrow become reversed.

As for the polymorphism and object-oriented programming, these subjects are goes beyond of this article, so not described there.

Conclusion

Learn and pass the job interview does not mean solid knowledge and programing technique deep understanding. As soon as the practical use case of dependency inversion arises, then immediately, as a rule, for beginners, a trouble occurs. And, speaking carefully, it is so strange, that there is no publications, books, or media, which has a short and clear explanation of fifth of principles of SOLID.

Eventually, using presented knowledge, a programmer simplify new modules adding. It means, that when adding new hardware, an input or output device for example, it will be much faster and easier, and most important will not entail existing code base changes.

References

  1. Original article
  2. Dependency inversion principle
  3. SOLID

--

--