This is that last part of a five part series about SOLID class design principles by
Robert C. Martin. The SOLID principles focus on achieving code that is maintainable, robust, and reusable. In this post, I will discuss the Dependency
Inversion Principle.
The Dependency Injection Principle (DIP): High level modules should not depend upon low level modules. Both should depend upon abstractions.
Imagine a world without plugs and sockets. The computer is directly
soldered into an electrical wire in the wall. Whenever you buy a
motherboard you also get a mouse, keyboard and monitor, but they're all
directly soldered onto the motherboard by the manufacturer. Everything
works fine, but things get complicated when you want to remove or
replace anything. If you try to replace the mouse:
- You risk damaging the motherboard
- It takes forever to solder
- Soldering is error prone because the new mouse has different wires
A world without plugs and sockets sounds ridiculous. Yet we
programmers have a tendency to pull out the metaphorical soldering iron
and hard-wire our classes together as we're making them. If the classes
are hard-wired together, and you want to replace one of them:
- You risk damaging code that uses the class
- It takes forever to find and change every place that the class is used
- Inserting the replacement class is error prone because it is slightly different to the old class
The Dependency Injection Principle is basically a way of adding
plugs and sockets to your code. It allows you to create your high level
modules (the computer) independent of the low level modules (the mouse).
The low level modules can be created later, and are easily replaceable.