Junior — Middle
Kas saaksite selgitada sõltuvuste pööramise põhimõtet ja selle tähtsust tarkvarasüsteemide kujundamisel?
sobes.tech AI
Vastus AI-lt
Dependency Inversion Principle (DIP) is one of the five SOLID principles and 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 concrete implementations of dependencies, it should work through interfaces or abstract classes. This increases the 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 the message sending implementation without modifying NotificationService, and also facilitates injecting mocks for testing.