AlgoViz

Interface segregation (ISP)

medium 50 min

No client should be forced to depend on methods it does not use.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:23

Interface segregation

1:06Reel

More reels

One idea each, a minute or less.

Play all in Bytesized Learning

Spot it: interface segregation

0:34Reel

Theory

Read or listen first. About 2 min.

What it is

The interface segregation principle (ISP) says: clients should not be forced to depend on methods they do not use. It is the I in SOLID.

The important word is client. A client is code that calls an interface. ISP does not ask how many methods a class has. It asks how many methods each caller must know, although it calls only a few.

So the interface belongs to the caller. If three kinds of callers use one class in three ways, there are three small interfaces, called roles. The class may implement all three and stay one class.

Why it exists

A fat interface couples its callers to each other. Someone needs a new method for billing, and the code that only prints must be compiled, tested and delivered again.

It also forces classes to lie. A simple printer that must implement scan and fax has three bad choices: do nothing, throw, or return null. Each is a broken promise, see Liskov substitution.

And it gives away too much. A report that receives an object with delete can delete. A report that receives only read cannot, not even by mistake.

A short history

  1. 1990s

    By Martin's account the idea came from consulting for Xerox, where one large Job class served printing, stapling and more, and each small change meant a long rebuild. The way out was an interface per kind of task.

  2. 1996

    Robert C. Martin describes the principle in their fourth Engineering Notebook column for the C++ Report. The example is a door with an alarm: every door becomes a client of a timer, although only one kind of door needs it.

  3. 1997

    Java 1.1 brings listener interfaces for windows and mice. A mouse listener has five methods, so the library adds MouseAdapter with empty bodies: nobody must write the other four.

  4. 2009

    Go is released. A type satisfies an interface without naming it, so a caller can declare a small interface for itself. Its standard library is known for interfaces with one method such as Reader and Writer.

  5. 2017

    PEP 544 is written. typing.Protocol, in Python since version 3.8, lets a caller declare the few methods it needs, and checkers match any class by shape.

Words to know

Client
Code that calls an interface.
Fat interface
One that has more methods than any single client uses.
Role interface
The methods that one kind of client needs, named after that need.
Header interface
All public methods of one class, copied into an interface. The opposite of a role.
Stub
A method written only because the interface demands it.
Interface pollution
Methods that a subtype needs, pushed into a base type for everyone.
Cohesion of an interface
How often its methods are used together by the same client.
Structural typing
A class fits an interface by its shape, without saying so.
Default method
A method with a body inside an interface.
Capability
An object that allows exactly what its methods allow.

The solution, twice

Reach the regular design first. Then go where a FAANG interviewer digs.

How it works

Step through the idea, or press Play.

Step 1 of 4

List the callers. Who uses this type?

Understand it

Start here

Forty buttons for one lamp

Asha has a lamp. The lamp has an on and an off. The remote in Asha's hand has forty buttons, because it was made for everything in the house.

Asha and the remote
Only the lamp, please

Frames 1 and 2 are the client's pain, 3 the implementer's, 4 the maintainer's. Frames 5 to 7 are the principle, and 8 is its limit.

The smell

A device that can do everything, on paper

An office has an interface MultiFunctionDevice with print, scan, fax, copy, staple and email. Then the mail room buys a printer that only prints.

Python
from abc import ABC, abstractmethodclass MultiFunctionDevice(ABC):    @abstractmethod    def print(self, doc): ...    @abstractmethod    def scan(self): ...    @abstractmethod    def fax(self, doc, number): ...class SimplePrinter(MultiFunctionDevice):    def print(self, doc): return f"printed {doc}"    def scan(self): raise NotImplementedError("cannot scan")   # forced to write this    def fax(self, doc, number): pass                           # worse: looks like successdef archive_paper(device: MultiFunctionDevice):    return device.scan()p = SimplePrinter()print(p.print("letter"), "|", p.fax("letter", "555"))try:    archive_paper(p)except NotImplementedError as e:    print("crash:", e)
Before. The type says: can scan. The object says: no, at run time, in front of a customer.
Edit and run it in your browser

The bad shape: one interface in the middle of everyone

«interface»MultiFunctionDevice+ print(doc)+ scan(): Doc+ fax(doc, number)+ copy(doc)+ staple(doc)+ email(doc, to)

1/4One interface

Six methods. It seems tidy: one type for all devices.

usesimplements

Two clients that have nothing in common are tied together by the box in the middle.

The good shape: one role per need

MailRoom+ printAll()ArchiveJob+ scanAll()FaxDesk+ send()

1/4Clients first

Three clients, three needs.

usesimplements

Passing the simple printer to the archive job does not compile. Copyable, Stapleable and Emailable follow the same way.
Python
from typing import Protocolclass Printable(Protocol):    def print(self, doc: str) -> str: ...class Scannable(Protocol):    def scan(self) -> str: ...class SimplePrinter:    def print(self, doc): return f"printed {doc}"class OfficeCopier:    def print(self, doc): return f"printed {doc}"    def scan(self): return "page 1"def mail_room(p: Printable): return p.print("letter")def archive_paper(s: Scannable): return s.scan()print(mail_room(SimplePrinter()), "|", mail_room(OfficeCopier()), "|", archive_paper(OfficeCopier()))# archive_paper(SimplePrinter())   a type checker refuses this line
After. Each function names what it needs. There is nothing to throw.
Edit and run it in your browser

Method

Draw the table: who calls what

Guessing where to cut leads to interfaces that look neat and fit nobody. The callers tell you. Put them in rows, the methods in columns, and mark what is really called.

A factory, with workers who are people and robots

CallerworkeattakeBreaksleepattendMeetingwriteReport
Shift plannerx
Canteenxx
Night shift roomsx
Calendarx
Managementx
RoleWorkableFeedableFeedableRestableMeetingAttendeeReportable
eat and takeBreak are always used by the same caller, so they stay together. This is why there are five roles and not six.

And the other side: who can keep which role

ClassWorkableFeedableRestableMeetingAttendeeReportable
HumanWorkerxxxxx
RobotWorkerxx
With one Worker interface the robot has four stubs, and the canteen's loop over all workers stops at the first robot.

The canteen and the robot

With roles the canteen holds a list of Feedable. A robot cannot get into that list.

Should these two methods live in one interface?

Yes to a tie between them wins over the wish for small interfaces. lock without unlock helps nobody.

Signs

How a fat interface shows itself

SignIn codeWho suffers
Empty methodsvoid fax(Doc d) { }Callers: silence looks like success
Not supportedthrow new UnsupportedOperationException()Callers: crash at run time
Return null or a defaultreturn null; // not applicableCallers: the crash comes later, elsewhere
Comments// not used by this classReaders
Large test doublesA mock with 20 methods for a test of oneTest authors
RebuildsA change in billing compiles the printer serviceEveryone, every day
Names with Manager, Service, UtilUserService with 31 methodsThose who look for the right one

Role interfaces

  • Named after a need: Printable, Feedable, OrderReader
  • Written beside the client that uses them
  • Few methods, used together
  • A class implements as many as it can keep
  • Test double: one or two methods

Header interface

  • Named after the class: IUserService
  • A copy of all its public methods
  • Grows with every request
  • Classes write stubs
  • Test double: a mocking tool is needed

What you gain

  • Smaller dependencies

    A client knows only what it calls.

  • Easier tests

    A fake with one method, written in two lines.

  • Freedom to change

    One role changes, the other clients sleep.

  • Clear contracts

    Each interface says one thing, so it can be kept.

  • Less coupling

    Clients are not tied together by a shared type.

  • No dummy code

    Implementers write only what they mean.

The first example

Martin's door, and two ways to separate

In the 1996 article a TimedDoor must sound an alarm when it stays open too long. It needs a timer, and the timer calls timeOut on its clients. The quick way makes Door a TimerClient. Now every door has a timeOut method. That is interface pollution.

Separation by an adapter

Timer+ register(ms, client)«interface»TimerClient+ timeOut()«interface»Door+ lock()+ unlock()+ isOpen()

1/3Two needs

A timer needs something to call. A caller of doors needs to lock and unlock.

usesimplements

The other way: TimedDoor implements both Door and TimerClient. Shorter, and fine when the names fit. The Adapter pattern also helps when the names clash, or when one door has several timeouts.

Judgement

When to cut, and when to leave it

UserService has 31 methods. Login calls 2 of them, the profile page 4, the admin tool 25. What do you do?

BreaksThirty-one interfaces
How
One method each.
Limit
Constructors with twelve parameters. Methods that share a rule are torn apart.
Choose when
Never as a rule.
BreaksIUserService with 31 methods
How
Extract interface, as the tool offers.
Limit
One more file and the same coupling.
Choose when
When a framework needs an interface for its proxy.
WorksSplit the class in three
How
Three services.
Limit
Good if they also have different data and reasons, which is single responsibility. Wrong if they share one transaction.
Choose when
The class itself has several jobs.
StrongTwo role interfaces, the class stays
How
Authenticator for login, ProfileReader for the page. The admin tool keeps the class.
Limit
The class is still large.
Choose when
The callers differ and the data is one.

ISP and its neighbours

PrincipleLooks atAsks
Single responsibilityThe class from insideHow many reasons to change?
Interface segregationThe class from each caller's sideHow much must this caller know?
Liskov substitutionThe implementerCan it keep every promise? Small interfaces make it possible
Dependency inversionThe direction of arrowsDoes the interface belong to the caller? ISP says how large it is
Law of DemeterChains of callsDo I talk to strangers?

Summary

The whole topic in one minute.

Look at the callers, not at the class. Group the methods by who calls them, and give each group an interface named after the need. One class may implement many.

Empty bodies, not supported errors and mocks with twenty unused methods are the signs. The gain is fewer rebuilds, honest classes, small test doubles and less power handed around.

Do not cut too small. Methods that are always used together, or that share a rule, stay together. Forty interfaces with one button each are as hard to use as one with forty.

  • Clients should not depend on methods they do not use.
  • The interface belongs to the caller: role, not header.
  • Draw the table of callers and methods before you cut.
  • One class may implement many roles. ISP does not split the class.
  • Stubs, not supported errors and huge mocks are the signs.
  • Keep together what is used together or tied by a rule.

Sources