Dependency Inversion Principle
The dependency inversion principle in SOLID: make business rules depend on abstractions they own, so databases and services can be swapped and faked in tests.
The dependency inversion principle is the D in SOLID. It says that the code holding your business rules should not depend on databases, mail servers or other details. Both should depend on an interface that the business code owns. Of the five principles, it is the one that most directly decides whether your code can be tested.
The topic starts with the principle and a reminder service that creates its own MySQL connection, so its test cannot run without a database server. It then introduces dependency injection, the usual way to apply the principle, and refactors the service step by step. Two examples follow: a test that swaps the database for a fake in memory, and Spring, a Java framework that does the wiring for you.
The last cards show an interface that is inverted in name only, and give you a weather report to make testable.
By the end you can tell policy from detail, say where an interface belongs, make a dependency replaceable in a test, and tell injection from inversion.
Contents
9 cardsnot started