Sobes.tech
Junior — Middle

Can you explain what the principle of dependency inversion is and why it is important 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 using specific implementations of other classes, it should work with abstractions (e.g., interfaces). The concrete implementations are injected from outside (via constructor, properties, or methods).

Why is this important:

  • It increases flexibility and extendability of the code.
  • It simplifies testing (dependencies can be easily replaced with mocks).
  • It reduces coupling between components.

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 through abstraction
    }

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

Here, UserService does not depend on a specific FileLogger but on the ILogger interface, which allows easy changing of the logger implementation.