What’s the Dependency Inversion Principle?

Get a brief introduction to the dependency inversion principle.

The dependency inversion principle states that a higher-level object should never depend on a concrete implementation of a lower-level object; both should depend on abstractions.

Any object-oriented language will have a way of specifying a contract to which any concrete class or module should adhere. Usually, this is known as an interface.

The interface is something that defines the signature of all the public members that the class should have, but, unlike a class, an interface doesn’t have any logic inside of those members. It doesn’t even allow us to define a method body to put the logic in.

But as well as being a contract that defines the accessible surface area of a class, an interface can be used as a data type in variables and parameters. When used this way, it can accept an instance of absolutely any class that implements the interface.

And this is where dependency inversion comes from. Instead of passing a concrete class into our methods and constructors, we pass the interface that the class in question implements.

The class that accepts an interface as its dependency is a higher-level class than the dependency. The passing interface is done because your higher-level class doesn’t care what logic will be executed inside of its dependency if any given method is called on the dependency. All it cares about is that a way with a specific name and signature exists inside the dependency.

Get hands-on with 1200+ tech skills courses.