System Design ( Day - 40 )

Manoj KumarManoj Kumar
2 min read

SOLID Principles | Dependency Inversion principle

Dependency Inversion principle
High Level module should not depend on low level module but rather both should depend on abstraction.
It means there is one high level module and low level module, these both should not talk with each other directly, but there should be a mediator like an abstraction or an interface, or some contracts, these modules should be talking to each other through this contracts only.

For Example High Level is the Application and Low level is the Database, so these should not talk to each other, there should be a interface between them like High level should talk to interface and interface should talk to Database and so on.

Decoupling: Prevents rigid hierarchies where high-level policy classes are tied directly to low-level utility classes. this will break the open close principle.

Violation:

class AuthService {
  private EmailSender sender = new EmailSender();
  void register(user) {
    // …
    sender.sendWelcome(user.email);
  }
}

Refactoring: Invert the dependency via abstraction and injection:

interface MessageSender { send(recipient, message); }
class EmailSender implements MessageSender { … }

class AuthService {
  private MessageSender sender;  // depends on abstraction
  AuthService(MessageSender sender) {
    this.sender = sender;
  }
  void register(user) {
    // …
    sender.send(user.email, "Welcome!");
  }
}

AuthService now works with any MessageSender (SMS, Push, etc.) injected at runtime.

Benefits

  • Promotes testability (mock or stub dependencies).

  • Enables swapping implementations without recompiling high-level code.

0
Subscribe to my newsletter

Read articles from Manoj Kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Manoj Kumar
Manoj Kumar