Card 01/ 09

ConceptDifficulty: Beginner1 min

Dependency Inversion: Business Rules Should Not Depend on Details

A password reminder should not need to know that users live in MySQL.

The dependency inversion principle says that high-level code should not depend on low-level code; both should depend on an abstraction, and the abstraction should belong to the high-level side. This card explains what high-level and low-level mean, and which arrow in a class diagram the principle turns round.

High-level policy is the code that states your business rules: who gets a password reminder, when an order ships free, how a discount is worked out. Low-level detail is the code that talks to the outside world: a MySQL query, an SMTP connection, an HTTP call to a payment provider. Policy is why the program exists. Details are how it reaches the world today, and they are the parts most likely to be replaced.

In most programs written without thought, dependencies run in the obvious direction: the reminder service creates a MySQL connection and calls it. The policy depends on the detail. A change of database means editing the reminder rules, and testing the reminder rules needs a database.

The dependency before and after inversion

In the diagram, the arrow from the service to MySQL is replaced by two arrows pointing at UserSource. MySQL's arrow now points towards the policy, which is the inversion the name refers to. Robert C. Martin set the principle out in a 1996 article.

A lamp and a wall socket are a fair picture. The lamp depends on the socket standard, not on the power station, and the power station is built to supply that same standard, so either can be replaced without touching the other. The analogy breaks in one place: nobody writes a socket standard for one lamp, while in code the policy owns its interface and shapes it to what it needs.

← → move through sections and cards