Sobes.tech
Middle

What is dependency inversion principle (SOLID principle)?

sobes.tech AI

Answer from AI

Dependency inversion is a principle from the SOLID set that states:

  • High-level modules should not depend on low-level modules directly.
  • Both should depend on abstractions (e.g., interfaces).
  • Abstractions should not depend on details, and details should depend on abstractions.

This reduces coupling between components, making the code easier to test and maintain.

Example in C#:

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

public class ConsoleLogger : ILogger
{
    public void Log(string message) => Console.WriteLine(message);
}

public class UserService
{
    private readonly ILogger _logger;

    public UserService(ILogger logger)
    {
        _logger = logger;
    }

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

Here, UserService depends on the ILogger abstraction, not on the specific ConsoleLogger implementation. This allows easy swapping of the logger implementation without changing UserService.