Tuesday, May 2, 2023

SOLID - Dependency Inversion Principle explanation with sample C# code

The Dependency Inversion Principle (DIP) is a principle in object-oriented programming that states that high-level modules should not depend on low-level modules. Instead, both should depend on abstractions. Furthermore, abstractions should not depend on details. Details should depend on abstractions.

Here is an example of how to implement the DIP in C#:
public interface ILogger
{
    void Log(string message);
}

public class ConsoleLogger : ILogger
{
    public void Log(string message)
    {
        Console.WriteLine($"Logging to console: {message}");
    }
}

public class DatabaseLogger : ILogger
{
    public void Log(string message)
    {
        // Code to log message to database
    }
}

public class ErrorReporter
{
    private readonly ILogger _logger;

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

    public void ReportError(string errorMessage)
    {
        _logger.Log($"Error occurred: {errorMessage}");
    }
}
In this example, we have an 'ILogger' interface that defines a 'Log' method, and two logger classes, 'ConsoleLogger' and 'DatabaseLogger', that implement the 'ILogger' interface.

We then have an 'ErrorReporter' class that depends on an 'ILogger' abstraction instead of a concrete implementation. This allows us to inject any implementation of the 'ILogger' interface into the 'ErrorReporter' class. By doing so, we have inverted the dependency from the 'ErrorReporter' class to the 'ILogger' interface, following the DIP.

Overall, adhering to the DIP helps us create code that is more modular, easier to maintain, and more flexible. By depending on abstractions instead of concrete implementations, we can easily switch out implementations without affecting the rest of our code.

No comments:

Post a Comment