The Plain Picture#
A TV remote with 80 buttons when you only ever use power, volume and channel. Worse: to make a new remote, the manufacturer must wire up all 80 buttons even if the TV doesn't support most of them.
The Real Name#
Interface Segregation Principle (ISP): no class should be forced to depend on methods it doesn't use. Prefer several small, focused interfaces over one big "fat" one.
Under the Hood#
The violation:
interface NoteStore {
Note find(long id);
List<Note> search(String text);
void save(Note n);
void delete(long id);
void exportToPdf(long id);
void syncToGoogleDrive(long id);
}A read-only cache must implement save, delete, exportToPdf and syncToGoogleDrive — probably by throwing exceptions (the LSP problem
from Ch 4). And a class that only reads notes still depends on the whole thing, so any change to the export methods forces it to recompile.
The fix — split by what clients actually need:
interface NoteReader { Note find(long id); List<Note> search(String text); }
interface NoteWriter { void save(Note n); void delete(long id); }
interface NoteExporter { void exportToPdf(long id); }
class PostgresNoteStore implements NoteReader, NoteWriter { ... } // a class can implement several (03_java_oop.md Ch 6)
class CachedNoteReader implements NoteReader { ... } // implements only what it can do
class SearchPage { private final NoteReader notes; ... } // depends on the minimum it needsJava's own library does this: Comparable, Runnable, Iterable, AutoCloseable each have exactly one method.
Check yourself
3 questionsState ISP.
Show answerHide answer
Clients shouldn't be forced to depend on methods they don't use — prefer small, focused interfaces.
How does a fat interface lead to LSP violations?
Show answerHide answer
Classes that can't support some of its methods end up throwing exceptions or doing nothing for them, breaking callers' expectations.
Name two one-method interfaces from Java's standard library.
Show answerHide answer
Any two: Comparable, Runnable, Iterable, AutoCloseable, Comparator (one abstract method).