Junior — Middle
Could you give an example of using the dependency inversion principle in real development?
sobes.tech AI
Answer from AI
The Dependency Inversion Principle (DIP) states that high-level modules should not depend on low-level modules directly, but both should depend on abstractions.
Example in Java:
// Abstraction
public interface MessageService {
void sendMessage(String message);
}
// Concrete implementation
public class EmailService implements MessageService {
public void sendMessage(String message) {
System.out.println("Sending email: " + message);
}
}
// Class depending on abstraction, not on concrete implementation
public class Notification {
private MessageService service;
public Notification(MessageService service) {
this.service = service;
}
public void notifyUser(String message) {
service.sendMessage(message);
}
}
// Usage
public class Main {
public static void main(String[] args) {
MessageService emailService = new EmailService();
Notification notification = new Notification(emailService);
notification.notifyUser("Hello!");
}
}
Here, the Notification class depends on the MessageService interface, not on the specific implementation EmailService. This allows easy swapping of implementations (for example, to an SMS service) without changing the Notification code. Such an approach improves testability and extensibility of the code.