LOW-LEVEL DESIGN · SOLID PRINCIPLES · I · 11 OF 48

Interface Segregation Principle in Java: Small Role Interfaces

The I in SOLID, shown with a smart-home hub whose one fat SmartDevice interface forces a plug to fake brightness, temperature and lock methods. Learn why fat interfaces hurt callers and implementers, how to split them into small role interfaces shaped by what each client needs, how far to split, and where the idea shows up in Java and LLD interviews.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
1 / 17

Press play to hear the narration, or step through at your own pace. The Java example is below.

Java example

One file, Java 17, 158 lines, with a small main() demo. Save it as InterfaceSegregationDemo.java, then run javac InterfaceSegregationDemo.java && java InterfaceSegregationDemo.

import java.util.List;

/** Interface segregation: one fat SmartDevice interface, then small role interfaces. */
public class InterfaceSegregationDemo {

    public static void main(String[] args) {
        System.out.println("--- Before: one fat interface ---");
        List<SmartDevice> everything = List.of(new FatSmartBulb(), new FatSmartPlug());
        for (SmartDevice device : everything) {
            try {
                device.setBrightness(20);
            } catch (UnsupportedOperationException e) {
                System.out.println("night scene broke: " + e.getMessage());
            }
        }
        System.out.println("plug battery: " + new FatSmartPlug().batteryPercent() + " (a magic value)");

        System.out.println();
        System.out.println("--- After: small role interfaces ---");
        SmartBulb bulb = new SmartBulb("hall bulb");
        SmartPlug plug = new SmartPlug("kettle plug");
        Thermostat thermostat = new Thermostat("living room");
        DoorLock frontDoor = new DoorLock("front door", 14);

        new NightMode(List.of(bulb), List.of(frontDoor)).run();
        new AwayMode(List.of(bulb, plug, thermostat)).run();
        new BatteryMonitor(List.of(frontDoor)).check();
        // new NightMode(List.of(plug), List.of()); // does not compile: a plug is not Dimmable
    }
}

// ---------------------------------------------------------------
// BEFORE: every device must implement every method.
// ---------------------------------------------------------------
interface SmartDevice {
    void turnOn();
    void turnOff();
    void setBrightness(int percent);
    void setTargetTemp(int celsius);
    void lock();
    void unlock();
    int batteryPercent();
}

class FatSmartBulb implements SmartDevice {
    @Override public void turnOn() { System.out.println("bulb on"); }
    @Override public void turnOff() { System.out.println("bulb off"); }
    @Override public void setBrightness(int percent) { System.out.println("bulb at " + percent + "%"); }
    @Override public void setTargetTemp(int celsius) { throw new UnsupportedOperationException("bulb"); }
    @Override public void lock() { } // pretends
    @Override public void unlock() { } // pretends
    @Override public int batteryPercent() { return -1; } // magic value
}

class FatSmartPlug implements SmartDevice {
    @Override public void turnOn() { System.out.println("plug on"); }
    @Override public void turnOff() { System.out.println("plug off"); }
    @Override public void setBrightness(int percent) { throw new UnsupportedOperationException("plug: dim"); }
    @Override public void setTargetTemp(int celsius) { throw new UnsupportedOperationException("plug"); }
    @Override public void lock() { } // pretends
    @Override public void unlock() { } // pretends
    @Override public int batteryPercent() { return -1; } // magic value
}

// ---------------------------------------------------------------
// AFTER: small roles. Devices implement only what they can do.
// ---------------------------------------------------------------
interface Switchable {
    void turnOn();
    void turnOff();
}

interface Dimmable {
    void setBrightness(int percent);
}

interface TemperatureControl {
    void setTargetTemp(int celsius);
}

interface Lockable {
    void lock();
    void unlock();
}

interface BatteryPowered {
    int batteryPercent();
}

record SmartPlug(String name) implements Switchable {
    @Override public void turnOn() { System.out.println(name + " on"); }
    @Override public void turnOff() { System.out.println(name + " off"); }
}

record SmartBulb(String name) implements Switchable, Dimmable {
    @Override public void turnOn() { System.out.println(name + " on"); }
    @Override public void turnOff() { System.out.println(name + " off"); }
    @Override public void setBrightness(int percent) { System.out.println(name + " at " + percent + "%"); }
}

record Thermostat(String name) implements Switchable, TemperatureControl {
    @Override public void turnOn() { System.out.println(name + " heating on"); }
    @Override public void turnOff() { System.out.println(name + " heating off"); }
    @Override public void setTargetTemp(int celsius) { System.out.println(name + " to " + celsius + " C"); }
}

record DoorLock(String name, int battery) implements Lockable, BatteryPowered {
    @Override public void lock() { System.out.println(name + " locked"); }
    @Override public void unlock() { System.out.println(name + " unlocked"); }
    @Override public int batteryPercent() { return battery; }
}

// Clients: each asks only for the roles it uses.

class NightMode {
    private final List<Dimmable> lights;
    private final List<Lockable> locks;

    NightMode(List<Dimmable> lights, List<Lockable> locks) {
        this.lights = List.copyOf(lights);
        this.locks = List.copyOf(locks);
    }

    void run() {
        System.out.println("[night mode]");
        lights.forEach(light -> light.setBrightness(20));
        locks.forEach(Lockable::lock);
    }
}

class AwayMode {
    private final List<Switchable> devices;

    AwayMode(List<Switchable> devices) {
        this.devices = List.copyOf(devices);
    }

    void run() {
        System.out.println("[away mode]");
        devices.forEach(Switchable::turnOff);
    }
}

class BatteryMonitor {
    private final List<BatteryPowered> devices;

    BatteryMonitor(List<BatteryPowered> devices) {
        this.devices = List.copyOf(devices);
    }

    void check() {
        System.out.println("[battery check]");
        for (BatteryPowered device : devices) {
            int level = device.batteryPercent();
            System.out.println(device + ": " + level + "%" + (level < 20 ? " - replace soon" : ""));
        }
    }
}

Notes

The problem

The hub team starts with one interface called smart device. It has turn on and turn off, set brightness, set target temperature, lock and unlock, and battery percent. It seemed simple at first: every device implements smart device, and the hub can treat them all the same. Then real devices arrived, and most of them can do only a few of these things.

SmartDevice
interface SmartDevice {
    void turnOn();
    void turnOff();
    void setBrightness(int percent);
    void setTargetTemp(int celsius);
    void lock();
    void unlock();
    int batteryPercent();
}

Forced to lie

Look at the smart plug. It can switch on and off, and that is all. But the interface forces it to write five more methods. Brightness and temperature throw an exception. Lock and unlock do nothing at all. Battery percent returns minus one, a magic number that means no battery. The plug is forced to pretend, and every pretend method is a bug waiting for a caller.

SmartPlug
public void setBrightness(int p) {
  throw new UnsupportedOperation...
}
public void setTargetTemp(int c) {
  throw new UnsupportedOperation...
}
public void lock() { /* nothing */ }
public void unlock() { /* nothing */ }
public int batteryPercent() {
  return -1; // mains powered
}

Why it hurts

Now the night mode scene takes a list of smart devices and dims them to twenty percent. When it reaches the plug, it crashes. The type said every smart device can dim, and the type was wrong. Worse, any change to the big interface, like adding a colour method for bulbs, forces edits and rebuilds in the plug, the lock and the thermostat, even though none of them care about colour.

The idea

The principle says no client should be forced to depend on methods it does not use. Here client means any code on either side of the interface: the classes that implement it, and the code that calls it. The answer is several small role interfaces instead of one fat one. Each interface describes one role, shaped by what some caller actually needs.

The principle
  • no client should be forced
  • to depend on methods it
  • does not use
  • prefer several small role
  • interfaces over one fat one
  • shape each interface by what
  • a caller needs, not by
  • everything a thing can do

Role interfaces

We split smart device into five roles. Switchable turns things on and off. Dimmable sets brightness. Temperature control sets a target temperature. Lockable locks and unlocks. Battery powered reports a battery level. Each role is small, and each method sits next to the methods it naturally belongs with. Lock and unlock stay together, because nothing can do one without the other.

The split
interface Switchable {
    void turnOn(); void turnOff(); }
interface Dimmable {
    void setBrightness(int percent); }
interface TemperatureControl {
    void setTargetTemp(int celsius); }
interface Lockable {
    void lock(); void unlock(); }
interface BatteryPowered {
    int batteryPercent(); }

Devices pick roles

Now each device picks only the roles it can really play. The plug is just switchable. The bulb is switchable and dimmable. The thermostat is switchable and has temperature control. The door lock is lockable and battery powered. A Java class can implement many interfaces, so combining roles is easy. Not a single method throws or pretends anymore.

Who implements what
  • SmartPlug: Switchable
  • SmartBulb: Switchable,
  • Dimmable
  • Thermostat: Switchable,
  • TemperatureControl
  • DoorLock: Lockable,
  • BatteryPowered
  • no fake methods anywhere

Clients pick roles

The callers change too. Night mode needs things it can dim and things it can lock, so it asks for a list of dimmables and a list of lockables. Away mode only switches things off, so it asks for switchables. The battery monitor asks only for battery powered devices. Each client now depends on the smallest interface that does its job, and nothing else.

A client in code

In code, night mode takes a list of dimmables and a list of lockables in its constructor. Its run method dims each light to twenty percent and locks each lock. The best part is what you cannot do anymore. You cannot pass a plug as a dimmable. The compiler rejects it. The crash from earlier has become a compile error, which is the cheapest kind of bug.

NightMode
NightMode(List<Dimmable> lights,
          List<Lockable> locks) { ... }

void run() {
  for (Dimmable d : lights)
    d.setBrightness(20);
  for (Lockable l : locks)
    l.lock();
}

a plug cannot be passed in here

Run-through

Run night mode. It asks the bulb, seen only as a dimmable, to go to twenty percent. Then it asks the door lock, seen only as a lockable, to lock. Night mode has no idea the lock also has a battery, or that the bulb can switch off. It never sees methods it does not use, so changes to those methods can never break it.

How to cut

How do you decide where to cut? Start from the callers. List which methods each caller really uses, and group methods that are always used together, like lock and unlock. Do not split into one interface per method by reflex. Dozens of single method interfaces are as hard to follow as one fat one. The right size is whatever one kind of caller needs.

Choosing the pieces
  • start from the callers:
  • which methods does each
  • one actually call?
  • group methods that are used
  • together (lock + unlock)
  • do not make one interface per
  • method by reflex
  • too fine: dozens of tiny
  • types nobody can follow

Combining roles

Sometimes a caller really needs several roles at once. You can combine small interfaces into a bigger one, like smart light, which extends switchable and dimmable. Callers that need both ask for smart light, and others still ask for one role. One warning: Java default methods that just throw an exception do not fix a fat interface. They only hide the same lie in a different place.

Putting roles back together
interface SmartLight
    extends Switchable, Dimmable { }

class SmartBulb implements SmartLight

a caller that needs both asks
for SmartLight; others still
ask for just one role

default methods that throw:
  still the same smell

How to spot it

The warning signs are easy to recognise. Methods that throw unsupported operation exception, empty methods, or magic return values like minus one. Callers that use two methods out of fifteen. Test mocks that need to stub methods the test never calls. And a change to one method that forces many unrelated classes to be edited or rebuilt. Each one says the interface is too wide for someone.

Warning signs
  • overrides that throw
  • UnsupportedOperationException
  • empty methods or magic values
  • like -1 or null
  • callers use 2 of 15 methods
  • test mocks must stub methods
  • the test never calls
  • one change rebuilds many
  • unrelated classes

Where you see it

Java is full of small interfaces. Runnable has one method. Comparable has one. Auto closeable has one, and that is why try with resources works with so many classes. Iterable only needs an iterator, and collection and list build on top of it. The java util function package is a set of tiny roles. A counter example is the list interface, which marks add and remove as optional, so read only lists must throw.

In Java
  • Runnable: one method, run
  • Comparable: one, compareTo
  • AutoCloseable: one, close
  • Iterable: just iterator()
  • Collection and List add more
  • java.util.function: Supplier,
  • Consumer, Predicate
  • counter-example: List marks
  • add and remove "optional"

Related ideas

Interface segregation is the single responsibility principle applied to interfaces. It also protects Liskov substitution, because fat interfaces push classes to fake methods, and faked methods are broken promises. It prepares the ground for dependency inversion, since small interfaces are the cleanest things to depend on. And when you must use someone else's fat interface, an adapter can wrap it in a small role.

How it relates
  • single responsibility: same
  • idea, applied to interfaces
  • Liskov: fat interfaces push
  • classes to fake methods,
  • which breaks substitution
  • dependency inversion: small
  • interfaces make clean
  • abstractions to depend on
  • Adapter: wraps a fat API in a
  • small role

In LLD interviews

In LLD interviews, look for different kinds of callers. A vending machine has customer operations, like select and pay, and admin operations, like restock and collect cash. They should be separate interfaces, so customer code can never call restock. A library has borrower actions and librarian actions. A parking lot has entry gates and exit gates. The classic mistake is one huge device or user interface with every method.

Where it comes up
  • vending machine: Customer ops
  • apart from Admin ops
  • (restock, collect cash)
  • library: Borrower apart from
  • Librarian actions
  • parking lot: EntryGate and
  • ExitGate, not one Gate
  • mistake: one Device or User
  • interface with every method

Interview questions

What is the interface segregation principle?

No client should be forced to depend on methods it does not use. Instead of one large interface, provide several small role interfaces so that implementers and callers each deal only with the methods that matter to them.

What problems does a fat interface cause?

Implementers must write fake methods that throw or do nothing, callers cannot trust the type to describe what an object can really do, and any change to the interface forces edits or rebuilds in classes that never used the changed method.

How do you decide how to split a large interface?

Look at the callers and which methods each one actually uses, then group methods that are used together and change together. Each group becomes a role interface. Avoid splitting into one interface per method unless callers really use them alone.

How is ISP related to the single responsibility principle?

It is the same idea applied to interfaces: an interface should serve one kind of client or one role. SRP keeps classes focused, while ISP keeps the contracts that callers and implementers see focused.

How does a fat interface lead to Liskov violations?

Classes that cannot support every method end up throwing UnsupportedOperationException or doing nothing, which breaks the promise the interface makes. Callers relying on that promise then fail at runtime.

Do Java default methods solve the fat interface problem?

Not really. A default method that throws or does nothing just moves the fake implementation into the interface. Defaults are good for genuine shared behaviour, but if many classes cannot support a method, the interface should be split.

Give an example of interface segregation in the Java standard library.

Runnable, Comparable, AutoCloseable and the java.util.function interfaces each have a single abstract method, so many unrelated classes can implement exactly the role they need. Iterable only requires iterator(), and richer types like Collection build on it.

How would you apply ISP in a vending machine design?

Split customer-facing operations such as selectItem and insertMoney from admin operations such as restock and collectCash into separate interfaces. The customer UI depends only on the customer interface, so it cannot call admin methods by mistake.