Dependency Inversion Principle

Learn about the dependency inversion principle (DIP) in software design.

The dependency inversion principle (DIP) proposes an interesting design principle through which we protect our code by making it independent of things that are fragile, volatile, or out of our control. The idea of inverting dependencies is that our code should not adapt to details or concrete implementations, but rather the other way around: we want to force whatever implementation or detail to adapt to our code via a sort of API.

Abstractions have to be organized in such a way that they do not depend on details, but rather the other way around—the details (concrete implementations) should depend on abstractions.

Imagine that two objects in our design, A and B, need to collaborate. A works with an instance of B, but as it turns out, our module doesn't control B directly (it might be an external library, or a module maintained by another team, and so on). If our code heavily depends on B, when this changes the code will break. To prevent this, we have to invert the dependency: Make B have to adapt to A. This is done by presenting an interface and forcing our code not to depend on the concrete implementation of B, but rather on the interface we have defined. It is then B's responsibility to comply with that interface.

In general, we can expect concrete implementations to change much more frequently than abstract components. It is for this reason that we place abstractions (interfaces) as flexibility points where we expect our system to change, be modified, or extended without the abstraction itself having to be changed.

A case of rigid dependencies

The last part of our event's monitoring system is to deliver the identified events to a data collector to be further analyzed. A naïve implementation of such an idea would consist of having an event streamer class that interacts with a data destination, for example, Syslog.

Get hands-on with 1200+ tech skills courses.