Sobes.tech
Junior — Middle

Mis on peamine põhjus sõltuvuste pööramise printsiibi rakendamiseks tarkvaraarhitektuuris?

sobes.tech AI

Vastus AI-lt

The Dependency Inversion Principle (DIP) is applied to reduce coupling between system components and to increase its flexibility and testability.

The main reason for applying DIP is to make high-level modules independent of low-level modules, with both depending on abstractions (interfaces), not on concrete implementations. This allows easy replacement of implementations, simplifies maintenance and extension of the code.

Example in C#:

public interface ILogger
{
    void Log(string message);
}

public class FileLogger : ILogger
{
    public void Log(string message) { /* write to file */ }
}

public class UserService
{
    private readonly ILogger _logger;

    public UserService(ILogger logger)
    {
        _logger = logger; // dependency via abstraction
    }

    public void CreateUser(string name)
    {
        // user creation logic
        _logger.Log($"User {name} created.");
    }
}

Here, UserService depends on the ILogger interface, not on the concrete FileLogger implementation. This makes it easy to replace the logger, for example with DatabaseLogger, without changes in UserService.