Dependency Inversion Principle

High-level policy should not depend on low-level detail. Both depend on an abstraction, and the abstraction is shaped by the policy, not by the detail.

Overview

The Dependency Inversion Principle (DIP) is the D in SOLID. Robert C. Martin stated it in his third C++ Report column (May 1996) in two parts. A: high-level modules should not depend upon low-level modules; both should depend upon abstractions. B: abstractions should not depend upon details; details should depend upon abstractions.

High-level means the code that holds the business rules, the part that makes the application what it is. Low-level means the mechanisms it uses: a database driver, a file, a network client, a screen. The traditional structure has the rules call the mechanisms directly, so a change in a driver can force a change in a rule. DIP flips the arrow.

In practice the two parts look like this. Part A says policy and detail both depend on an abstraction, so the service takes a Repository interface, not a Postgres class. Part B says the abstraction is not shaped by the detail, so the interface says what the policy needs, not what the driver offers. A small program shows both at work.

The Copy program

Martin's example is a program that copies characters from a keyboard to a printer. The first version has a copy loop that calls read_keyboard and write_printer directly. The dependency arrows run from the copy loop, which is the policy, down to those two device functions. It works, but it can only ever copy from that keyboard to that printer. The copy loop is the only interesting logic, and it cannot be reused without the two devices it names. Add a disk file as a target and the loop grows an if; add more devices and the high-level loop fills with low-level branches.

The inverted version gives copy an abstract Reader and an abstract Writer. The keyboard and printer implement them, and so can a new device such as a file reader. Now the loop depends on nothing concrete, and the devices depend on the abstractions the loop defined.

Interview questions

  • What is the difference between Dependency Inversion and Dependency Injection?
  • How does DIP make code testable?
  • How do you implement DIP in Java, Python and Go?
  • What is a composition root and why does it matter?
  • What are the downsides of applying DIP everywhere?
  • How does DIP relate to hexagonal architecture?

Sign up free to read the full topic

More Low-Level Design topics

Start free on Cariara · Coding problems · System design studio