Junior — Middle
Can you explain the principle of dependency inversion and its importance 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. 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 using specific implementations of dependencies, it should work through interfaces or abstract classes. This increases flexibility and testability of the code.
Example in C#:
// Abstraction
public interface IMessageSender
{
void Send(string message);
}
// Concrete implementation
public class EmailSender : IMessageSender
{
public void Send(string message) {
Console.WriteLine($"Sending email: {message}");
}
}
// Class depending on abstraction
public class NotificationService
{
private readonly IMessageSender _messageSender;
public NotificationService(IMessageSender messageSender) {
_messageSender = messageSender;
}
public void Notify(string message) {
_messageSender.Send(message);
}
}
// Usage
var emailSender = new EmailSender();
var notification = new NotificationService(emailSender);
notification.Notify("Hello!");
This approach allows easy changing of message sending implementation without modifying NotificationService, and also conveniently substituting mocks for testing.