Interface Segregation Principle
is the 4th principle ofSOLID
principles. It is also known asISP
principle. It was first introduced byRobert C. Martin
in his 2000 paperDesign Principles and Design Patterns
.
The concept is simple, make the interfaces smaller and more specific to the use case. it is better to have multiple but smaller interfaces than a single large interface.
So basically, a class should not be forced to implement an interface or methods that it does not use.
Cohesion
: Interfaces should be highly cohesive. It means the interface methods should be related to each other, if they are not related then they should be separated into different interfaces.Responsibility
: Interfaces should have single responsibility.Let's take an example of aPrinter
class that can print, scan and fax. So we can create an interfaceMultiFunctionPrinter
that has all the methods ofPrinter
class.
interface MultiFunctionPrinter { print(): void; scan(): void; fax(): void; }
Now we have aSimplePrinter
class that can only print. So we can implement theMultiFunctionPrinter
interface inSimplePrinter
class.
class SimplePrinter implements MultiFunctionPrinter {
print(): void {
console.log("Printing...");
}
scan(): void {
throw new Error("Simple Printer can not scan.");
}
fax(): void {
throw new Error("Simple Printer can not fax.");
}
}
This is a total violation ofISP
principle. BecauseSimplePrinter
class is forced to implement thescan
andfax
methods that it does not use.
To make this run smoothly, we can separate the interface into three different interfaces.
interface Printer {
print(): void;
}
interface Scanner {
scan(): void;
}
interface Fax {
fax(): void;
}
Now we can implement the interfaces inSimplePrinter
class.
class SimplePrinter implements Printer {
print(): void {
console.log("Printing...");
}
}
If there is advanced printer class, it can implement multiple interfaces.
class AdvancedPrinter implements Printer, Scanner, Fax {
print(): void {
console.log("Printing...");
}
scan(): void {
console.log("Scanning...");
}
fax(): void {
console.log("Faxing...");
}
}
ISP
principle is very important to make the code more maintainable and flexible. It also helps to reduce the coupling between classes and not implementing unnecessary methods.