What is Interface segregation principle and how to implement it in C#?

CsharpServer Side ProgrammingProgramming

Clients should not be forced to depend upon interfaces that they don't use.

The Interface Segregation Principle states that clients should not be forced to implement interfaces they don't use.

Instead of one fat interface many small interfaces are preferred based on groups of methods, each one serving one submodule

Before Interface Segregation

Example

public interface IProduct {
   int ID { get; set; }
   double Weight { get; set; }
   int Stock { get; set; }
   int Inseam { get; set; }
   int WaistSize { get; set; }
}
public class Jeans : IProduct {
   public int ID { get; set; }
   public double Weight { get; set; }
   public int Stock { get; set; }
   public int Inseam { get; set; }
   public int WaistSize { get; set; }
}
public class BaseballCap : IProduct {
   public int ID { get; set; }
   public double Weight { get; set; }
   public int Stock { get; set; }
   public int Inseam { get; set; }
   public int WaistSize { get; set; }
   public int HatSize { get; set; }
}

After Interface Segregation

Example

public interface IProduct {
   int ID { get; set; }
   double Weight { get; set; }
   int Stock { get; set; }
}
public interface IPants {
   int Inseam { get; set; }
   int WaistSize { get; set; }
}
public interface IHat {
   int HatSize { get; set; }
}
public class Jeans : IProduct, IPants {
   public int ID { get; set; }
   public double Weight { get; set; }
   public int Stock { get; set; }
   public int Inseam { get; set; }
   public int WaistSize { get; set; }
}
public class BaseballCap : IProduct, IHat {
   public int ID { get; set; }
   public double Weight { get; set; }
   public int Stock { get; set; }
   public int HatSize { get; set; }
}
raja
Published on 25-Nov-2020 16:46:41
Advertisements