Sobes.tech
Junior — Middle

What is the role of the dependency inversion principle in software system design?

sobes.tech AI

Answer from AI

The Dependency Inversion Principle (DIP) is one of the five SOLID principles, which states that high-level modules should not depend on low-level modules, but both should depend on abstractions (such as interfaces or abstract classes). This helps reduce component coupling and increase system flexibility.

In software system design, DIP allows:

  • Ensuring loose coupling between components.
  • Simplifying replacement and testing of system parts (e.g., through dependency injection).
  • Increasing code reusability.

An example in Python using abstractions:

from abc import ABC, abstractmethod

class NotificationSender(ABC):
    @abstractmethod
    def send(self, message: str):
        pass

class EmailSender(NotificationSender):
    def send(self, message: str):
        print(f"Sending email: {message}")

class NotificationService:
    def __init__(self, sender: NotificationSender):
        self.sender = sender

    def notify(self, message: str):
        self.sender.send(message)

# Usage
email_sender = EmailSender()
service = NotificationService(email_sender)
service.notify("Hello!")

Here, NotificationService depends not on a specific implementation of EmailSender, but on the abstraction NotificationSender. This makes it easier to replace the notification sending method without changing the service.