Concepts of Dependency Inversion

Posted on Apr 15, 2022

Click here for a code example.

The dependency inversion principle was introduced first by Robert C. Martin in the year of 1996.

It is a concept how to design applications to prevent rigidity, fragility and immobility.

It can be used where one class sends a message to another.

Citing M. Fowler the principle has two underlying concepts:

  1. High level modules should not depend upon low level modules. Both should depend upon abstractions.
  2. Abstractions should not depend upon details. Details should depend upon abstractions.

In this series I’ll show the concepts of dependency inversion and one example for it.

Why dependency inversion

When high level modules depend on low level modules, then changes on low level modules affect the higher ones.

This should not be the intended way, as the high level modules do contain important policy decisions and business models of an application. Furthermore they are the more interesting modules which we probably want to reuse.

The dangers of a layered system

In a layered system where high level components call low level components, we have the problem that we don’t have any control how a change in a lower layer will affect a higher layer.

See the following example from Martin Fowler where the Policy Layer depends on the Mechanism Layer. And where the Mechanism Layer depends on the Utility Layer.

A change of the Utility Layer would affect the Policy Layer! Really unfortunate.

The concept of dependency inversion

A better approach for this is shown in the image below - which also shows the dependency inversion.

The lower layers are represented by abstract classes. High level layers are depending on these abstract classes and the actual layers are derived from these abstract classes.

This means that the transitive dependency is broken and that we can reuse the Policy Layer in any context where the Mechanism Layer interface is fulfilled!