What is „Interface Segregation Principle” (ISP) ?
It is the fourth rule of the SOLID design rules (it stands for I in SOLID acronym).
Definition
Clients should not be forced to depend upon interfaces that they do no use.
Robert C. Martin (Uncle Bob)
In simpler words, we should avoid situation where class inheriting from interface do not use some parts of the interface. Interfaces should be specific and as small as possible.
Real-life example
Let’s say we want to implement classes for car, airplane and multifunctional car (like in Taxi movie).
public interface Vehicle { void drive(); void fly(); }
public class Car implements Vehicle { public void drive() { System.out.println("Driving a car"); } public void fly() { } }
public class Airplane implements Vehicle { public void drive() { } public void fly() { System.out.println("Flying a plane"); } }
public class MultiFunctionalCar implements Vehicle { public void drive() { System.out.println("Drive a multifunctional car"); } public void fly() { System.out.println("Fly a multifunctional car"); } }
UML diagram of our application:
Fly method in Car class is empty, the same about drive method in Airplane class. It means that Vehicle interface contains too many parts for our needs and due to that our program does not meet ISP rule.
To fix it, we need to split Vehicle interface into smalled interfaces e.g. ICar and IAirplance.
public interface ICar { void drive(); }
public interface IAirplane { void fly(); }
public class Car implements ICar { public void drive() { System.out.println("Driving a car"); } }
public class Airplane implements IAirplane { public void fly() { System.out.println("Flying a plane"); } }
public class MultiFunctionalCar implements ICar, IAirplane { public void drive() { System.out.println("Drive a multifunctional car"); } public void fly() { System.out.println("Fly a multifunctional car"); } }
Now classes implement only necessary methods, it means that interfaces are consistent with the ISP rule.
UML diagram of our application after refactoring:
Why should I follow „Interface Segregation Principle” ?
Thanks to this rule, the code is easier to extend and maintain. Less tricky interfaces also mean more clear code.
What to look for?
ISP is not the same as LSP. Focus in ISP is not about making classes replaceable, but rather on rethinking initial design and picking up proper abstractions when designing a system.