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.
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.
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.
- 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.
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.
- 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(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.
- 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.
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.
- 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.
- 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.
- 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.
- 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