SOLID is a very popular design concept in programming. Interface Segregation is part of SOLID Design. You may ask, what is SOLID?
SOLID are 5 software development principles or guidelines based on Object-Oriented design making it easier for you to make your projects scalable and maintainable.
In code, you have best-practices and rules. SOLID designs are like best-practices.
Interface Segregation
It says
Clients Should Not Be Forced To Depend Upon Interfaces That They Do Not Use.
Pretty straightforward.
What This Means
✔️ Create smaller and specific interfaces (role interfaces).
❌ Classes can implement interfaces they don't use.
Why do this?
Consider
A client depends upon a class that contains interfaces the client does not use, but other clients do use, then the first client will be affected by the changes other clients force upon the class used by the first client.
The Goal of this principle is to avoid these situations.
The pattern for other SOLID principles like Single Responsibility and Open Close is much similar : To avoid code breakages in the long run.
A Simple Use Case
Using the Bird example much similar to that discussed in Liskov Substitution.
interface Bird {
fly(): void;
walk(): void;
}
class Duck extends Bird{
fly(){
// Duck can fly
}
walk(){
// Duck can walk
}
}
class Ostrich extends Bird{
fly(){
// Ostrich cant fly... throw some error
}
walk(){
// Ostrich can walk
}
}
Here fly()
is enforced to an Ostrich class by the Duck class, since both implement the same interface and Duck does use fly()
. It is a clear violation of the Interface Segregation Principle.
Using the Interface Segregation Principle we refactor our code to be
interface BirdFly{
fly(): void;
}
interface BirdWalk{
walk(): void;
}
class Duck extends BirdFly, BirdWalk{
fly(){
// Duck can fly
}
walk(){
// Duck can walk
}
}
class Ostrich extends BirdWalk{
walk(){
// Ostrich can walk
}
}
We have now made role-specific interfaces and there is no inadvertent coupling.
Is It Practical?
Definitely, It is best to follow this principle whenever possible. However, if your requirements are satisfied and you can work around the inadvertent coupling, then sure you can avoid this principle.
Do you use Interface Segregation? Be sure to tell me your opinion in the comments.
What's Next
Why The Dependency Inversion Principle Is Worth Using.
Top comments (0)