LLD

SOLID Principles

Interface Segregation Principle

No caller should have to depend on methods it does not use. We build the delivery partners of a quick-commerce app twice, once behind one wide interface and once behind small interfaces shaped by their callers, and see what one new rule costs each time.

A quick-commerce app in Bengaluru promises groceries in ten minutes. Most of its delivery partners ride petrol bikes. Some ride cycles, and inside a few large gated societies, runners deliver on foot. The app has one interface, DeliveryPartner, for all three kinds of partner, and three different parts of the app call it.

The Interface Segregation Principle says that no caller should have to depend on methods it does not use.

The principle

An interface sits between two sides: the classes that call it and the classes that implement it. The principle asks us to shape an interface around what its callers need. When several callers need different things, each caller gets its own small interface.

A wide interface costs something on both sides. An implementer that has no answer for a method still has to write it, as a stub that throws or returns a made-up value. A caller that uses one part is tied to the rest, so a change to a method it never calls can still reach it.

It works like the Single Responsibility Principle, one level up. That principle groups a class's code by who asks for changes. This one groups an interface's methods by who calls them.

What it does not say

  • It is not about size. An interface with eight methods is fine if its one caller uses all eight. An interface with three methods breaks the principle if two callers each use a different part of it.
  • It does not mean one method per interface. Methods that one caller always uses together belong in one interface. We come back to this below.

Example: delivery partners

The first version has one interface for everything the app asks about a partner:

interface DeliveryPartner {    int maxLoadGrams();     void assign(Order order);     String drivingLicence();     String vehicleNumber();     long fuelAllowanceCents(int km);}

Three classes call it, and each one uses a different part:

  • OrderDispatcher finds a free partner who can carry the order's weight and assigns the order. It uses maxLoadGrams() and assign(order).
  • ComplianceJob runs every morning and blocks any rider whose driving licence or vehicle registration is not valid. It uses drivingLicence() and vehicleNumber().
  • PayoutCalculator adds a fuel allowance of $0.10 a kilometre to a bike rider's weekly pay. It uses fuelAllowanceCents(km).

Each kind of partner must implement all five methods. A petrol bike rider has an answer for each one. A cycle rider has no driving licence and no number plate, so CycleRider has nothing true to return for them:

final class CycleRider implements DeliveryPartner {    // maxLoadGrams() and assign(order) have real answers: a cycle carries 8 kg.     @Override    public String drivingLicence() {        throw new UnsupportedOperationException("A cycle needs no driving licence");    }     @Override    public String vehicleNumber() {        throw new UnsupportedOperationException("A cycle has no number plate");    }     @Override    public long fuelAllowanceCents(int km) {        return 0; // a cycle uses no fuel    }}

WalkingRunner has the same three methods.

Three callers, one interface
Every kind of partner must implement every slice, even a slice with no true answer for it. The purple DeliveryPartner interface has five methods in three slices, one under each caller that uses it. Below it, each row is a kind of partner. PetrolBikeRider has a real answer in every slice. CycleRider and WalkingRunner answer the dispatcher's slice, but their licence methods throw, in red, and their fuel method exists only to return 0. The red bar shows the result: ComplianceJob stops at the first cycle rider.Every kind of partner must implement every slice, even a slice with no true answer for it. The purple DeliveryPartner interface has five methods in three slices, one under each caller that uses it. Below it, each row is a kind of partner. PetrolBikeRider has a real answer in every slice. CycleRider and WalkingRunner answer the dispatcher's slice, but their licence methods throw, in red, and their fuel method exists only to return 0. The red bar shows the result: ComplianceJob stops at the first cycle rider.
Each caller uses one slice of DeliveryPartner, but every partner must implement all of it. Every kind of partner must implement every slice, even a slice with no true answer for it. The purple DeliveryPartner interface has five methods in three slices, one under each caller that uses it. Below it, each row is a kind of partner. PetrolBikeRider has a real answer in every slice. CycleRider and WalkingRunner answer the dispatcher's slice, but their licence methods throw, in red, and their fuel method exists only to return 0. The red bar shows the result: ComplianceJob stops at the first cycle rider.

What the stubs cost

ComplianceJob is written against DeliveryPartner, so it accepts a list of every partner:

final class ComplianceJob {    private final LicenceRegistry registry;     ComplianceJob(LicenceRegistry registry) {        this.registry = registry;    }     /** Runs every morning. Returns the partners who may not take orders today. */    List<DeliveryPartner> blockedPartners(List<DeliveryPartner> partners) {        List<DeliveryPartner> blocked = new ArrayList<>();        for (DeliveryPartner partner : partners) {            if (!registry.isValid(partner.drivingLicence(), partner.vehicleNumber())) {                blocked.add(partner);            }        }        return blocked;    }}

The first cycle rider in the list throws UnsupportedOperationException, and the job stops. It blocks nobody that morning. A bike with a lapsed registration can take orders all day, even if the job had already found it.

The quick fix is a line at the top of the loop that skips CycleRider and WalkingRunner with instanceof. The job runs again, but now it names two classes. The next kind of partner without a licence crashes it again, until someone adds a third name. A CycleRider cannot stand in for a DeliveryPartner in ComplianceJob, because two of its methods throw. That breaks the Liskov Substitution Principle too.

The change request

Operations asks for one more morning check: a bike whose pollution under control (PUC) certificate has expired may not take orders. The developer adds LocalDate pucExpiry() to DeliveryPartner.

One new method, five edits
A rule about motor vehicles edits two classes that have no motor vehicle. Amber outlines mark what the PUC change edits. The purple DeliveryPartner interface gains pucExpiry(). ComplianceJob checks the date and PetrolBikeRider returns it. CycleRider and WalkingRunner each get a new stub that throws, in red. OrderDispatcher and PayoutCalculator are not edited, but they still depend on the changed interface.A rule about motor vehicles edits two classes that have no motor vehicle. Amber outlines mark what the PUC change edits. The purple DeliveryPartner interface gains pucExpiry(). ComplianceJob checks the date and PetrolBikeRider returns it. CycleRider and WalkingRunner each get a new stub that throws, in red. OrderDispatcher and PayoutCalculator are not edited, but they still depend on the changed interface.
A rule about petrol bikes edits two classes that have no motor vehicle. A rule about motor vehicles edits two classes that have no motor vehicle. Amber outlines mark what the PUC change edits. The purple DeliveryPartner interface gains pucExpiry(). ComplianceJob checks the date and PetrolBikeRider returns it. CycleRider and WalkingRunner each get a new stub that throws, in red. OrderDispatcher and PayoutCalculator are not edited, but they still depend on the changed interface.

Five of the seven classes and interfaces are edited. DeliveryPartner gets the method, ComplianceJob checks it, and PetrolBikeRider returns its date. CycleRider and WalkingRunner do not compile until each one gets another stub that throws. Neither has a motor vehicle, yet both are edited for a rule about motor vehicles. OrderDispatcher and PayoutCalculator need no edit, but they depend on the changed interface. A default method that throws would spare those two edits, but the stub would still be there, hidden in the interface, and the compiler would no longer point at the classes that cannot answer.

Following the principle

We split the interface by caller. Each caller gets an interface with the methods it uses, and nothing else:

/** What OrderDispatcher needs. */interface OrderCarrier {    int maxLoadGrams();     void assign(Order order);} /** What ComplianceJob needs. */interface LicensedRider {    String drivingLicence();     String vehicleNumber();} /** What PayoutCalculator needs. */interface FuelAllowanceEarner {    long fuelAllowanceCents(int km);}

PetrolBikeRider implements all three, because every caller has a use for a bike rider. CycleRider and WalkingRunner implement only OrderCarrier, and their stubs are gone. LicensedRider and FuelAllowanceEarner have the same one implementer, but they stay apart because two different callers use them. A change to the fuel allowance then reaches only the payout side.

Hub, which onboards partners at a dark store, is the one place that knows a partner's kind. It puts each new partner into the lists that fit:

final class Hub {    private final List<OrderCarrier> dispatchPool = new ArrayList<>();    private final List<LicensedRider> licensedRiders = new ArrayList<>();    private final List<FuelAllowanceEarner> fuelPayees = new ArrayList<>();     void onboard(PetrolBikeRider rider) {        dispatchPool.add(rider);        licensedRiders.add(rider);        fuelPayees.add(rider);    }     void onboard(CycleRider rider) {        dispatchPool.add(rider);    }     // onboard(WalkingRunner) matches the cycle version. Getters are left out.}

ComplianceJob now takes a List<LicensedRider>. Adding a CycleRider to that list is a compile error, so a cycle rider cannot reach the job, and the job needs no instanceof line.

Now the same change request arrives. pucExpiry() goes into LicensedRider, PetrolBikeRider returns its date, and the job checks it:

List<LicensedRider> blockedRiders(List<LicensedRider> riders, LocalDate today) {    List<LicensedRider> blocked = new ArrayList<>();    for (LicensedRider rider : riders) {        boolean papersValid = registry.isValid(rider.drivingLicence(), rider.vehicleNumber());        if (!papersValid || rider.pucExpiry().isBefore(today)) {            blocked.add(rider);        }    }    return blocked;}
The same change, after
With one interface per caller, the PUC rule edits only the licence side. Each caller uses one purple role interface. CycleRider and WalkingRunner implement only OrderCarrier. PetrolBikeRider implements all three. Amber outlines mark the three edits: pucExpiry() in LicensedRider, PetrolBikeRider returning its date, and ComplianceJob checking it. The four boxes marked no change are not opened.With one interface per caller, the PUC rule edits only the licence side. Each caller uses one purple role interface. CycleRider and WalkingRunner implement only OrderCarrier. PetrolBikeRider implements all three. Amber outlines mark the three edits: pucExpiry() in LicensedRider, PetrolBikeRider returning its date, and ComplianceJob checking it. The four boxes marked no change are not opened.
Each caller has its own interface, so the PUC rule edits only the licence side. With one interface per caller, the PUC rule edits only the licence side. Each caller uses one purple role interface. CycleRider and WalkingRunner implement only OrderCarrier. PetrolBikeRider implements all three. Amber outlines mark the three edits: pucExpiry() in LicensedRider, PetrolBikeRider returning its date, and ComplianceJob checking it. The four boxes marked no change are not opened.

Three are edited this time: LicensedRider, PetrolBikeRider and ComplianceJob. CycleRider, WalkingRunner, OrderDispatcher and PayoutCalculator are not opened, and none of them depends on LicensedRider.

Splitting too far

OrderDispatcher uses both of its methods for one job: it checks the weight, then assigns the order. Suppose someone reads the principle as one method per interface and splits OrderCarrier into LoadLimited and Assignable. The dispatcher now needs an object that is both, and its signature has to say so:

<T extends LoadLimited & Assignable> Optional<T> dispatch(Order order, List<T> freeCarriers) {    for (T carrier : freeCarriers) {        if (order.weightGrams() <= carrier.maxLoadGrams()) {            carrier.assign(order);            return Optional.of(carrier);        }    }    return Optional.empty();}

Hub cannot even declare its dispatch pool as List<LoadLimited & Assignable>, because Java does not allow that type, so it ends up wanting a combined OrderCarrier again. The split gains nothing. No partner implements one interface without the other, and no caller uses one without the other. The test is the caller: methods that the same caller uses together stay in one interface.

When not to

An interface with one caller has nothing to split. With several callers, the cost of a wide interface shows up in two ways: an implementer writes a stub, or a change to one method edits classes that never call it. If the app had only bike riders, every partner would answer every method and no class would need a stub. Keeping DeliveryPartner whole would then be a fair choice, and the split could wait until the first partner without a licence joins.

In an interview

When you draw an interface, say which class calls it and which methods that class needs. If two callers need different methods, draw two interfaces and let one class implement both. The Adapter pattern page gives SmsSender only the one method its caller needs.

Common mistakes:

  • Grouping methods by what a class has. "Everything a bike has" is not a role. The licence check and the fuel payout have different callers, so they are two interfaces, even though only bikes implement them.
  • Writing a stub that throws. UnsupportedOperationException in an implementation is a sign that the interface asks for too much.
  • Patching the caller with instanceof. The caller is working around an interface that is too wide, and every new kind needs another check.
  • One method per interface. Methods that one caller uses together belong together.

Summary

  • No caller should have to depend on methods it does not use. Shape each interface around its callers.
  • A wide interface makes implementers write stubs, and a stub that throws breaks substitution as well.
  • A change to one method of a wide interface can edit classes that never use that method.
  • Split by caller into small role interfaces. One class can implement several of them.
  • Methods that one caller uses together stay in one interface. One method per interface is too far.

Spot a mistake, or something unclear? . Or get in touch.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.