What is Dependency Injection / Inversion (DI/DIP)?
DI/DIP, told as a story about a writer who only needs to know a standard socket, instead of wiring directly into one specific machine.
The writer writes to fit one exact machine.The manuscript is wired straight into that one machine.
If Press Model A breaks, the writer is stuck too.The manuscript is wired so tightly to that machine, the writer can't move at all.
DI/DIP means the writer only knows the standard socket, while what gets plugged in is decided from outside.The editor plugs in the right machine from outside — that's injection.
A standard socket, instead of direct wiring, makes swapping easy.Both the high-level writer and the low-level machine answer to the same socket spec.
Too many standards, and it gets confusing instead.Put standards only where they're needed, and swapping stays easy.
DIP is the principle that the writer (high-level) isn't tied directly to the machine (low-level) — both sides look only at a standard socket (an abstraction). DI is the technique of plugging the machine in from outside.
The Dependency Inversion Principle (DIP) says high-level modules shouldn't depend on low-level modules — both should depend on an abstraction (an interface). Dependency Injection (DI) is the implementation technique that passes (injects) a concrete implementation of that abstraction from outside, instead of an object creating it itself. DIP is the 'D' in the SOLID principles.
When grown-ups say it
- Dependency Inversion Principle
- A principle where both high- and low-level sides answer only to a standard. It's the D in SOLID.
- Dependency Injection
- The technique of plugging the machine in from outside. The writer never creates or picks the machine themselves.
- Interface / Abstraction
- The standard socket itself. It promises only the spec, not the machine's internals.
- Coupling
- How tightly the writer and machine are tied together. Direct wiring is tight coupling; a socket is loose coupling.
- Encapsulation
- Hiding the machine's details from the writer's view. Another principle DIP leans on. → the writer's locked drawer
- Test Double / Mock
- A fake stand-in machine, used only for testing. As long as the socket matches, it can stand in for the real machine.
- Inversion of Control
- Handing control of the flow from your own code to an outside framework. DI is one specific form of IoC.
- Refactoring
- Changing structure but not behavior — e.g. turning direct wiring into a socket. The plot stays the same — only the wiring gets reworked. → same plot, retouched sentences