- Published on
[SOLID] Interface Segregation Principle
- Authors
- Name
- Khánh
When we use
Statement
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.[1] ISP splits interfaces that are very large into smaller and more specific ones so that clients will only have to know about the methods that are of interest to them.
It's advisable to separate interfaces by specific functionalities. You can refer to the first principle to understand how interfaces should be divided.
Example
We have an Animal class
interface IAnimal {
eat: () => void;
}
public class Dog implements IAnimal {
public eat(){
// implement eat of dog
}
}
public class Cat implements IAnimal {
public eat(){
// implement eat of cat
}
}
However, when adding other classes like different animals and methods such as swim, fly, hunt, etc., these classes also have to implement corresponding methods. This makes extension more challenging. The solution to this is to separate them into smaller interfaces for easier maintenance.
interface IAnimal {
eat: () => void;
}
interface IFish extends IAnimal {
swim: () => void;
}
interface IBird extends IAnimal {
fly: () => void;
}
class Dog implements IAnimal {
public eat() {
// implement eat of dog
}
}
class Cat implements IAnimal {
public eat() {
// implement eat of cat
}
}
class Bird implements IBird {
public fly() {
console.log('fly');
}
public eat() {
console.log('eat');
}
}
Conclusions
Applying the ISP (Interface Segregation Principle) makes the system more flexible, easier to maintain, and extend. However, it should be used judiciously to avoid having too many interfaces in the system.