According to the Interface Segregation Principle (ISP), a client shouldn't be made to implement interfaces they don't utilise. Stated otherwise, a class shouldn't be made to rely on methods it doesn't employ. It is preferable to have smaller, more focused interfaces as opposed to large, monolithic ones.
Let's take the example of a band consisting of singers, drummers, and guitarists in the setting of musicians. We may design unique interfaces for every kind of musician rather than having a single Musician interface that has every technique conceivable for all kinds of musicians:
Let's demonstrate the Interface Segregation Principle in action:
interface IGuitarist {
playGuitar(): void;
}
interface IDrummer {
playDrums(): void;
}
interface ISinger {
sing(): void;
}
Now, each musician class can implement only the interface relevant to their role. For example:
class RockGuitarist implements IGuitarist {
playGuitar(): void {
console.log("Playing electric guitar in a rock band");
}
}
class JazzDrummer implements IDrummer {
playDrums(): void {
console.log("Playing jazz drum beats");
}
}
class PopSinger implements ISinger {
sing(): void {
console.log("Singing catchy pop melodies");
}
}
// Let's play music:
const popSinger = new PopSinger();
popSinger.sing()
const rockGuitarist = new RockGuitarist();
rockGuitarist.playGuitar();
const jazzDrummer = new JazzDrummer();
jazzDrummer.playDrums();
Our code is more flexible and maintainable when we adhere to the Interface Segregation Principle, which makes sure that each class only depends on the methods it requires.
See you in the next article of this series.