Member-only story
What is the Dependency Inversion Principle? (With Code Example) — SOLID
The connections between classes should be as loose as possible. Especially, higher-level classes should not depend on lower-level classes directly.
The connection of a class, method, or feature to other classes that use it should be made as small as possible. Changes in a lower-level class should not affect the higher-level classes.
When something changes in a high-level class, the lower-level classes need to change to match. But, when something changes in a low-level class, the high-level classes should not break.
So, how do we get rid of all these problems?
The answer is Dependency Inversion. This means that high-level classes should not depend on low-level classes. Instead, both should depend on abstract ideas. We can create a layer of abstraction between the high-level and low-level classes.
- High-Level Classes -> Abstraction Layer -> Low-Level Classes
Let’s make it easier to understand with an example. Let’s say we have a Notification
class, and we can send emails and SMS messages using it.
Here is a class that can send emails:
public class Email {
public void sendEmail() {
//Send email
}
}