Card 09/ 09
Recap: Dependency Inversion
The policy owns the interface, the detail implements it, and injection connects them.
The dependency inversion principle keeps business rules independent of the machinery they use.
- Policy should not depend on detail. Both depend on an abstraction, and the abstraction belongs to the policy.
- The sign of a violation is a detail created inside policy code: a
new MySQLDatabasein a service, or a test that needs a server. - Injection is the usual technique. Pass dependencies in through the constructor, so the caller chooses the implementation.
- Injection is not inversion. Injecting a concrete class still ties the policy to it; the parameter's type must be the policy's interface.
- The interface lives with the policy, not beside its implementation and not in a module nobody owns.
- Shape the interface by the need. If its methods mirror the database, the policy still changes when the database does.
- The payoff is in tests. A fake implementation lets business rules run with no database, no network and a fixed clock.
- Frameworks wire; they do not design. Spring injects whatever type you name.
← → move through sections and cards