Interface segregation (ISP)
medium 50 minNo client should be forced to depend on methods it does not use.
Video lesson · Chapter 1 of 6
Make a prediction
Interface segregation
1:06Reel
More reels
One idea each, a minute or less.
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
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.
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.
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.
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.
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.
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.
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.
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)The bad shape: one interface in the middle of everyone
1/4One interface
Six methods. It seems tidy: one type for all devices.
usesimplements
The good shape: one role per need
1/4Clients first
Three clients, three needs.
usesimplements
Copyable, Stapleable and Emailable follow the same way.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 lineMethod
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
| Caller | work | eat | takeBreak | sleep | attendMeeting | writeReport |
|---|---|---|---|---|---|---|
| Shift planner | x | |||||
| Canteen | x | x | ||||
| Night shift rooms | x | |||||
| Calendar | x | |||||
| Management | x | |||||
| Role | Workable | Feedable | Feedable | Restable | MeetingAttendee | Reportable |
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
| Class | Workable | Feedable | Restable | MeetingAttendee | Reportable |
|---|---|---|---|---|---|
| HumanWorker | x | x | x | x | x |
| RobotWorker | x | x |
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
Feedable. A robot cannot get into that list.Should these two methods live in one interface?
lock without unlock helps nobody.Signs
How a fat interface shows itself
| Sign | In code | Who suffers |
|---|---|---|
| Empty methods | void fax(Doc d) { } | Callers: silence looks like success |
| Not supported | throw new UnsupportedOperationException() | Callers: crash at run time |
| Return null or a default | return null; // not applicable | Callers: the crash comes later, elsewhere |
| Comments | // not used by this class | Readers |
| Large test doubles | A mock with 20 methods for a test of one | Test authors |
| Rebuilds | A change in billing compiles the printer service | Everyone, every day |
| Names with Manager, Service, Util | UserService with 31 methods | Those 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
1/3Two needs
A timer needs something to call. A caller of doors needs to lock and unlock.
usesimplements
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
Authenticatorfor login,ProfileReaderfor 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
| Principle | Looks at | Asks |
|---|---|---|
| Single responsibility | The class from inside | How many reasons to change? |
| Interface segregation | The class from each caller's side | How much must this caller know? |
| Liskov substitution | The implementer | Can it keep every promise? Small interfaces make it possible |
| Dependency inversion | The direction of arrows | Does the interface belong to the caller? ISP says how large it is |
| Law of Demeter | Chains of calls | Do 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
- Robert C. Martin: The Interface Segregation Principle (C++ Report, 1996)
- Interface segregation principle, origin at Xerox
- Martin Fowler: RoleInterface
- Go: code review comments, interfaces
- Effective Go
- Go: net/http
- PEP 544: Protocols
- Python: collections.abc
- Java: MouseAdapter
- Java: ExecutorService
- Java: java.sql.Wrapper
- Android: GestureDetector
- .NET: IReadOnlyList
- Spring Data: defining repository interfaces
- Docker: plugin API