SOLID Principles – Interface segregation principle
In the field of software engineering, the interface segregation principle (ISP) states that no code should be forced to depend on methods it does not use.
From Wiki
The interface segregation principle (ISP) states that no-client should be forced to depend on the methods or the objects it doesn’t use. ISP splits interfaces that are very huge into smiler and more specific ones, so that the clients will only have to know about the methods or the objects that are of interest to them. Such shrunken interface are also called “role interface.“
ISP is intended to keep the system decoupled and thus easier to refactor, change, and redeploy. Beyond object-oriented design (OOD), ISP is a key principle in the design of distributed system in general and microservices in particular. ISP is similar to the High Cohesion principle of General Responsibility Assignment Software Patterns (GRASP) or Principles. ISP is also one of the six IDEALS principles of microservice design.
How to implement the interface segregation principle?
public void Solution()
{
Console.WriteLine("Interface Segregation Principle");
ICar _car = new Car(); ;
IAirplane _airplane = new Airplane();
IMultiFunctionalVehicle multiFunctionalVehicle = new MultiFuncationCar(_car, _airplane);
multiFunctionalVehicle.Drive();
multiFunctionalVehicle.Fly();
}
internal interface ICar
{
void Drive();
}
internal interface IAirplane
{
void Fly();
}
internal interface IMultiFunctionalVehicle : ICar, IAirplane
{ }
public class Car : ICar
{
public void Drive()
{
//actions to drive a car
Console.WriteLine("Driving a car");
}
}
public class Airplane : IAirplane
{
public void Fly()
{
//actions to fly a plane
Console.WriteLine("Flying a plane");
}
}
internal class MultiFuncationCar : IMultiFunctionalVehicle
{
private readonly ICar _car;
private readonly IAirplane _airplane;
public MultiFuncationCar(ICar car, IAirplane airplane)
{
_car = car;
_airplane = airplane;
}
public void Drive()
{
//actions to start driving car
Console.WriteLine("Drive a multifunctional car");
_car.Drive();
}
public void Fly()
{
//actions to start flying
Console.WriteLine("Fly a multifunctional car");
_airplane.Fly();
}
}
Reference
- Interface segregation principle – Wiki
- CodeMaze: SOLID Principles in C# – Interface Segregation Principle