Dependency inversion (DIP)
medium 40 minThe rules of your program should not name the tools they run on.
Video lesson · Chapter 1 of 6
Make a prediction
Dependency inversion
1:02Reel
More reels
One idea each, a minute or less.
Spot it: dependency inversion
0:33Reel
Theory
Read or listen first. About 2 min.
What it is
The dependency inversion principle (DIP) has two sentences. High-level modules should not depend on low-level modules: both should depend on abstractions. And abstractions should not depend on details: details should depend on abstractions.
High level means policy: what the program is for, such as when an order may be placed. Low level means mechanism: SQL, HTTP, files, a vendor's library. Position in a file or number of methods has nothing to do with it.
It is the D in SOLID. The word *inversion* is about the arrow in the source code. A layered program usually has rules that import the database. After the change, the database code imports an interface that belongs to the rules.
Why it exists
Policy lives long and tools change. When a rule creates its own database client, a new client is an edit in the rule. With many rules, it is an edit in all of them.
A rule that creates its tools can only be tested with those tools: a real database, a real card charge. A rule that receives them can be tested in milliseconds with a small stand-in.
It lets two teams agree on one interface and then work apart.
A short history
1996
Robert C. Martin publishes The Dependency Inversion Principle as one of the Engineering Notebook columns in the C++ Report.
2004
Martin Fowler's article of January names dependency injection and compares constructor, setter and interface injection with a service locator.
2005
Alistair Cockburn writes up hexagonal architecture, also called ports and adapters: an application that works without its user interface and its database.
2013
Brett Schuchert, on Martin Fowler's site, shows DIP on real projects and warns that it can help or hurt depending on the problem.
Words to know
- Policy
- A rule of the business. High level.
- Detail
- A mechanism that carries the rule out. Low level.
- Port
- The interface a policy owns, written in its own words.
- Adapter
- A class that fits a tool to a port and translates names, types and errors.
- Dependency injection
- Handing an object what it needs instead of letting it create or look it up. A technique.
- Inversion of control
- A wider idea: a framework calls your code. Injection is one form of it.
- Composition root
- The one place, near main, that chooses classes and connects objects.
- Container
- A library that does the connecting from a list of bindings.
- Fake
- A simple working implementation for tests, such as a store in memory.
The solution, twice
Reach the regular design first. Then go where a FAANG interviewer digs.
How it works
Step through the idea, or press Play.
Find the policy. Which sentence would a non-programmer recognise?
Understand it
Start here
Any lamp with a ring
The smell
A rule that names its tools
Before: policy points at details
1/3The rule
Checkout decides when an order counts as placed. This is why the shop exists.
uses
The turn
Where the arrow flips
After: details point at the policy's ports
1/3Policy and its ports
Checkout keeps its three needs as interfaces. They live in the same package as Checkout.
depends onusesimplements
Two kinds of arrow
Four terms that get mixed up
| Term | Question it answers | Example |
|---|---|---|
| DIP | Who owns the interface, and which way do imports point? | OrderStore lives beside Checkout |
| Dependency injection | How does an object receive what it needs? | Checkout(store) |
| Inversion of control | Who calls whom? | A web framework calls your handler |
| Container | Who does the wiring? | A library with a list of bindings |
Ownership
The consumer writes the interface
An interface copied from a tool inverts nothing. If OrderStore has beginTransaction, executeSql and ResultSet, it is the database with another name. Write the port from the sentence the policy would say: *remember this order and its receipt*.
A port
- Named for the need:
OrderStore - Takes and returns policy types
- Throws the policy's errors
- Only the methods this policy calls
A mirror of the tool
- Named for the tool:
IPostgresClient - Returns rows, cursors, HTTP responses
- Leaks vendor exceptions
- Forty methods, two used
Small ports come from interface segregation. That every adapter honours the same promises is Liskov substitution. That a new adapter needs no edit of the policy is open/closed.
Delivery
Ways to hand a dependency over
Constructor
Checkout(store). Needed always, set once. The default, and the list of needs is visible.Setter
setLog(log). For something optional with a safe default. Otherwise the object can exist half built.Interface
The class implements
StoreAware.inject(store)and a framework calls it. Ties the class to that framework.Method or function argument
place(order, now). For values that differ per call, such as the time or the current user.Service locator
Locator.get(OrderStore). The class asks a global. Needs are hidden, and a test must fill the global.
In motion
One order through the ports
Policy speaks, adapters translate
Judgement
Does this need a port?
Before you add an interface
Checkout needs a database. How do you connect them?
BreaksCreate it inside
- How
self.db = PostgresOrders()in the constructor.- Limit
- Each test needs the database, and each change of tool edits the rule.
- Choose when
- A script that will be thrown away.
WorksInject the concrete class
- How
Checkout(PostgresOrders(url)).- Limit
- Creation has moved out, so settings can differ. The source arrow still points at the tool.
- Choose when
- The tool is stable and can run in tests, for example a local file.
StrongOwn a port and inject an adapter
- How
OrderStorebeside the policy,SqlStorebeside the driver, joined inmain.- Limit
- One more type, and contract tests so fake and real agree.
- Choose when
- Policy worth testing alone meets the outside world.
Limits
What it does not give you
Summary
The whole topic in one minute.
Point source code arrows at the policy. The policy owns a small port, adapters implement it, and the composition root joins them. The run-time call still goes from policy to tool.
Injection is how objects receive things. Inversion is who owns the interface. You can inject a concrete class and have no inversion at all.
Use it at real boundaries: input and output, vendors, time, randomness. A port in front of every class is only extra reading.
- Policy owns the port. Details implement it.
- Source arrows point at policy. Run-time calls go the other way.
- Inject through the constructor. Create objects in one place.
- A port speaks in the policy's words, types and errors.
- One set of contract tests for the fake and the real adapter.
- No port without a boundary or a second behaviour.
Sources
- Robert C. Martin: The Dependency Inversion Principle (C++ Report, 1996, archived)
- Martin Fowler: Inversion of Control Containers and the Dependency Injection pattern
- Brett Schuchert: DIP in the Wild
- Alistair Cockburn: Hexagonal architecture
- Spring: dependency injection
- .NET: dependency injection guidelines (captive dependency)
- Go: database/sql/driver
- Kubernetes: Container Storage Interface