10/12/2025

Dependency Inversion Principle


Instead of a class depending directly on another concrete class, it should depend on an interface or abstract class.This makes your code flexible, testable, and maintainable. Easy to switch implementations (e.g., Service1, Service2). Easy to test using mocks. Follows DIP and promotes clean architecture


interface IService
{
  public void ResetDevice();
}

public class Service1 : IService 
{
  public void ResetDevice() {// Sercice1 logic}
}

public class Service2 : IService 
{
  public void ResetDevice() {// Service2 logic}
}

public class Program
{
    public static void Main()
    {
        IService service;
        if(_soapVersion <= 1)
           service = new Service1();
        else
           service = new Service2();  //easily replaceable, swithable
    }
}
Without LSP:
Why the name inversion - The word "inversion" in Dependency Inversion Principle (DIP) refers to a reversal of the conventional direction of dependency in software design.
Without DIP: High-level modules (like business logic) depend on low-level modules (like database or email services). This means the flow of control and design is top-down, and high-level logic is tightly coupled to implementation details.
With DIP: Both high-level and low-level modules depend on abstractions (interfaces or abstract classes). The control is inverted: instead of high-level modules controlling low-level ones directly, they rely on abstractions that are implemented by low-level modules. - loosly coupled

No comments:

Post a Comment