Video in progress
What problem does the Interface Segregation principle solve?
A big "does everything" interface forces the implementing class to write methods it doesn't need and ties callers to changes that don't concern them. ISP says: split the interface into small pieces based on the clients.
📖 Answer
The problematic interface:
interface Worker {
void work();
void eat();
void attendMeeting();
}
class Robot implements Worker {
public void work() { ... }
public void eat() { throw new UnsupportedOperationException(); } // meaningless
public void attendMeeting() { throw new UnsupportedOperationException(); }
}
Methods filled with UnsupportedOperationException are the clearest sign of an ISP violation (and they break LSP too).
The split version:
interface Workable { void work(); }
interface Feedable { void eat(); }
class Human implements Workable, Feedable { ... }
class Robot implements Workable { ... }
A real backend example: UserService has 40 methods, and the admin panel, the mobile app and the reporting module each use 3-4 of them. If you split it into parts like UserQueryService and UserAdminService, both mocking in tests and understanding the code get easier.
Don't slice interfaces too fine either: a separate interface for every method makes the code harder to read too.
Sign up to mark studied questions and save your progress.