Short definition
The last principle resulting from the SOLID acronym is the title Dependency Inversion Principle. This rule is:
The principle of inversion of dependency assumes that high-level modules should not depend on low-level modules, but on abstraction.
To quickly understand what is going on here, let's use an example.
Some example
We will create our high-level module, which will be the Computer class. The computers we use every day have some pointing devices. These can be mice, touchpads and probably a few more. Their goal is to control the operation of the computer, so simplified our classes will look like this:
public class Computer {
private Mouse mouse;
public Computer(Mouse mouse) {
this.mouse = mouse;
}
public void enterTheFolder(){
mouse.makeDoubleClick();
}
}
public class Mouse {
void makeDoubleClick() {
//do something
}
}
Note that in the example above, our Computer class, which is a high-level module, depends on the Mouse class, which is a low-level module. To avoid this dependency, we will introduce the Pointer interface owned by the Computer class. Then the code will look like this:
public class Computer {
private Pointer pointer;
public Computer(Pointer mouse) {
this.pointer = mouse;
}
public void enterTheFolder() {
pointer.makeDoubleClick();
}
}
public interface Pointer {
public void makeDoubleClick();
}
public class Mouse implements Pointer {
@Override
public void makeDoubleClick() {
//do something
}
}
And this is how our high level module is no longer dependent on the low level module. Now we can create a new class that implements the Pointer interface and pass it in the constructor of the Computer class without any problems.
If you haven't looked at my other SOLID posts yet, please click here .
Pingback: SOLID - podstawa programowania obiektowego – Wojciech Siwek