Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / SOLID Principles

    I: The Interface Segregation Principle

    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

    Chapter 5 of 82 min read

    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:

    Java
    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:

    Java
    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 needs

    Java's own library does this: Comparable, Runnable, Iterable, AutoCloseable each have exactly one method.

    Check yourself

    3 questions
    1

    State ISP.

    Show answer

    Clients shouldn't be forced to depend on methods they don't use — prefer small, focused interfaces.

    2

    How does a fat interface lead to LSP violations?

    Show answer

    Classes that can't support some of its methods end up throwing exceptions or doing nothing for them, breaking callers' expectations.

    3

    Name two one-method interfaces from Java's standard library.

    Show answer

    Any two: Comparable, Runnable, Iterable, AutoCloseable, Comparator (one abstract method).