Interface Segregation Principle (ISP), states "Clients should not be forced to depend upon interfaces that they do not use"
This is again introduced by Sir Robert D. Martin, while consulting at xerox.
Similar to the
Single Responsibility Principle the goal of the Interface Segregation Principle is to reduce the side effects of frequent changes in the existing implementation.
Points to remember,
- No client needs to be forced to introduce with what is not necessary to them
- Rather than using one fat interface, splitting into smaller and relevant interfaces are advisable
Case Study from Xerox,
- Xerox created inhouse software to help printer system do tasks like stapling and faxing along with regular printer task
- The whole system requires change from scratch up
- That creates a whole lot of change and complexity
Example,
Below the interface is a one fat consisting of all the methods, now if something needs to introduce the whole implementation requires change and that is risky.
interface IPrint
{
void Print();
{
void Print();
void Scan();
void Fax();
}
void Fax();
}
We have solved this issue by separating SendEmail functionality from other classes to meet the Single Responsibility Principle.
The solution for the above example would,
interface IPrint
{
void Print();
{
void Print();
void Scan();
}
}
interface IFax
{
void Fax();
}
class Printer1: IPrint //Only has the ability to Print
{
{
public void Print()
{
{
}
public void Scan()
{
{
}
}
class Printer2: IPrint, IFax //Printer ability to Print and Fax both
{
{
public void Print()
{
{
}
public void Scan()
{
{
}
public void Fax()
{
}
}
We have separated the functionality by breaking it into interfaces rather than a single one. Now in Print1 that has the functionality of Print and Scan but not Fax so implementation, only IPrint interface will meet the goal. Printer2 is all in one so Print, Scan, and Fax functionality so along with IPrint we can have IFax interface to get the functionality of Fax in the same.
Here we have separated the responsibilities as well as distributed the interface from a big fat to multiple interfaces and achieved a high level of abstraction.