The Dependency Inversion Principle

Definition: Depend upon abstractions. Do not depend upon concrete classes.

Reducing dependencies to concrete classes in your code is a good thing.

This principle sounds a lot like “Program to an interface, not an implementation”. However, the Dependency Inversion Principle makes an even stronger statement about abstraction. It suggests that your high-level components should not depend on your low-level component; rather, they should both depend on abstractions.

A high-level component is a class with behavior defined in terms of other low-level components. For example, in the Factory Patterns scenario, PizaStore is a high-level component because its behavior is defined in terms of pizzas - it creates all the different pizza objects, and prepares, bakes, cuts, and boxes them, while the pizzas it uses are low-level components. PizzaStore is dependent on the concrete pizza classes.

Where is the “inversion” in Dependency Inversion principle?

The “inversion” in the name Dependency Inversion principle is there because it inverts the way you typically might think about your OO design.

Tags:

Factory Method is not the only technique for adhering to the Dependency Inversion principle, but it is one of the more powerful ones.

Factory patterns