Learning Dependency Inversion Principle
Dependency Inversion
Dependency Inversion states that high-level modules shouldn’t depend on low-level modules, but both should rely on abstractions. You should work with abstractions rather than classes or concrete implementations. When you do this, your components become reusable. Changes in a low-level module do not affect any other module. That’s called loose coupling. The two main parts of this principle are:
- High-level modules shouldn’t depend on low-level modules. Both should depend on abstractions.
- Abstractions shouldn’t depend on details. Details should depend on abstractions.
Understanding the Importance of Dependency Inversion
Imagine you could only use a specific set of tires on your car, and if you ever needed to replace them, you’d have to stick to the same brand and model. That’d be quite inconvenient. However, fortunately, you can use any other tire that meets the required specifications. The same goes for the fuel you use in your car. You don’t have to go to a specific gas station to get the same brand of fuel every time. Instead, you can get the same type of fuel at various locations throughout the country.
The Dependency Inversion Principle is quite popular, relatively easy to implement, and doesn’t add much complexity. To inject a dependency, you can use a constructor, field, or method injection, but constructor injection is usually preferred. This makes it easy to see what dependencies a class has just by looking at the class instantiation.
In the following demo, you’ll learn how to apply the Dependency Inversion Principle to your e-commerce app.