The Interface Segregation Principle (ISP) is one of the SOLID principles of object-oriented design.
The interface Segregation Principle states that a client should not be forced to depend on methods that it does not use.
In other words, the interface Segregation Principle says, a class should only expose the methods that are relevant to its clients, and not expose methods that are not needed. This helps to ensure that a class is easy to use, easy to understand, and easy to change.
Here is an Interface Segregation Principle example in C#,
Let’s say we have an interface called IMachine which has methods for starting, stopping, and operating the machine:
public interface IMachine
{
void Start();
void Stop();
void Operate();
}
Now suppose we have two different classes Printer and Scanner, which implements the IMachine interface. However, the Printer class only needs to implement the Start() and Stop() methods, while the Scanner class only needs to implement the Start() and Operate() methods.
If we were to implement the IMachine interface directly in both classes, we would end up with unnecessary methods in each class that are not relevant to its functionality. This violates the Interface Segregation Principle.
To fix this, we can create two new interfaces: IPrinter and IScanner, which inherit from IMachine and contain only the methods that each class needs:
public interface IPrinter : IMachine
{
// Printer-specific methods go here
}
public interface IScanner : IMachine
{
// Scanner-specific methods go here
}
Now we can implement each interface in the appropriate class:
public class Printer : IPrinter
{
public void Start()
{
Console.WriteLine("Printer starting...");
}
public void Stop()
{
Console.WriteLine("Printer stopping...");
}
}
public class Scanner : IScanner
{
public void Start()
{
Console.WriteLine("Scanner starting...");
}
public void Operate()
{
Console.WriteLine("Scanner operating...");
}
}
By following the Interface Segregation Principle, we have created interfaces that are specific to each class’s functionality, and we have prevented each class from having to implement unnecessary methods.
This Interface Segregation Principle(ISP) makes our code more modular, easier to maintain, and less prone to errors.
Leave a Reply