Junior — Middle
Can you explain what is meant by the principle of dependency inversion in software development?
sobes.tech AI
Answer from AI
The Dependency Inversion Principle (DIP) is one of the five SOLID principles, which states:
- High-level modules should not depend on low-level modules. Both should depend on abstractions.
- Abstractions should not depend on details. Details should depend on abstractions.
This means that instead of a class directly creating or depending on specific implementations of other classes, it should depend on abstract interfaces or abstract classes. This increases flexibility and makes testing and maintaining the code easier.
Example in Java:
interface MessageService {
void sendMessage(String message);
}
class EmailService implements MessageService {
public void sendMessage(String message) {
System.out.println("Sending email: " + message);
}
}
class Notification {
private MessageService service;
// Dependency injection via constructor
public Notification(MessageService service) {
this.service = service;
}
public void notifyUser(String message) {
service.sendMessage(message);
}
}
// Usage
MessageService emailService = new EmailService();
Notification notification = new Notification(emailService);
notification.notifyUser("Hello!");
Here, the Notification class depends not on a specific implementation of EmailService, but on the abstraction MessageService. This allows easy changing of the service implementation without modifying the Notification class.