These are the notes for Low-Level Design (LLD) episode 15: the I in SOLID, the Interface Segregation Principle (ISP). A printer that can only print is forced to pretend it can scan and fax, and then stops compiling because of a feature it doesn't even have. From that pain we invent the fix: splitting interfaces into role interfaces and client-specific interfaces, plus the strangest interface of all, the marker interface. Every program was run with javac Main.java && java -cp . Main (Java 21); outputs and error messages are real.
1. The real-life problem: grandma's remote
Grandma wants to watch the news. She needs four buttons: power, channel, volume, off. Her remote has sixty, because the company made one remote for every possible user. Then an update rearranges the menu buttons, buttons she has never pressed, and she's lost again. She was tied to things she doesn't use. Software interfaces grow exactly like this remote.
2. Fat interfaces
An interface (episode 3) is a list of methods a class promises to provide. A client is any code that uses an interface (calls its methods or takes it as a parameter).
interface Machine { // one fat interface for every device
void print(String doc);
void scan(String doc);
void fax(String doc, String number);
}
class OfficeMachine implements Machine {
public void print(String doc) { System.out.println("Printing " + doc); }
public void scan(String doc) { System.out.println("Scanning " + doc); }
public void fax(String doc, String number) { System.out.println("Faxing " + doc); }
}
class HomePrinter implements Machine { // can only print
public void print(String doc) { System.out.println("Printing " + doc); }
public void scan(String doc) { throw new UnsupportedOperationException("No scanner"); }
public void fax(String doc, String number) { throw new UnsupportedOperationException("No fax"); }
}
public class Main {
public static void main(String[] args) {
Machine[] all = { new OfficeMachine(), new HomePrinter() };
for (Machine m : all) m.print("marksheet.pdf");
for (Machine m : all) m.scan("aadhaar-front.jpg");
}
}
Printing marksheet.pdf
Printing marksheet.pdf
Scanning aadhaar-front.jpg
Exception in thread "main" java.lang.UnsupportedOperationException: No scanner
at HomePrinter.scan(Main.java:13)
at Main.main(Main.java:20)
The home printer can only print, but Java makes it implement scan and fax, so it fakes them by throwing. The interface said it could scan. It lied. (That's also last episode's refused bequest: an LSP violation caused by a fat interface.)
A fat interface has many methods serving many different clients.
3. Interface pollution
The office model gains a stapler, so someone adds staple to Machine. HomePrinter is not touched:
interface Machine {
void print(String doc);
void scan(String doc);
void fax(String doc, String number);
void staple(String doc); // new: for the office model only
}
// OfficeMachine adds staple(); HomePrinter is unchanged
Main.java:13: error: HomePrinter is not abstract and does not override abstract method staple(String) in Machine
class HomePrinter implements Machine { // not touched at all
^
1 error
A class that has nothing to do with stapling fails to compile, because of a feature only another product has.
- Interface pollution: an interface gains methods that some of its implementers can't honour or don't need.
- Because everyone depends on the whole interface, every change to it reaches every class and every client, even those that never use the changed method.
4. The Interface Segregation Principle
No code should be forced to depend on methods it does not use.
Segregation just means separating. Robert C. Martin first used and formulated the principle while consulting for Xerox:
- Xerox had built a new printer system that could print, staple, fax and more.
- Almost every task used one
Jobclass: a fat class. A staple job knew about all the print job methods it never used. - As the software grew, even a small change took about an hour to redeploy, and development nearly stopped.
- Martin's fix: an interface layer, one interface per kind of job (a Staple Job interface, a Print Job interface, ...). The
Jobclass implemented them all, but each client saw only its own.
5. Role interfaces and client-specific interfaces
Ramesh runs a shop. Customers see a shopkeeper (sell, give change); his kid sees a parent (homework, pocket money). One person, many roles, and each person around him sees only the role they need.
| Ramesh's day | In Java |
|---|---|
| Customers see a shopkeeper | Printer (print) |
| His kid sees a parent | Scanner (scan) |
| Ramesh is all of them | OfficeMachine implements Printer, Scanner, Fax |
- Role interface: a small interface describing one role an object can play. Splitting a fat interface produces role interfaces.
- Client-specific interface: an interface shaped by what a client needs, not by everything a class can do.
interface Printer { void print(String doc); } // role interfaces:
interface Scanner { void scan(String doc); } // one small role each
interface Fax { void fax(String doc, String number); }
class OfficeMachine implements Printer, Scanner, Fax {
public void print(String doc) { System.out.println("Printing " + doc); }
public void scan(String doc) { System.out.println("Scanning " + doc); }
public void fax(String doc, String number) { System.out.println("Faxing " + doc); }
}
class HomePrinter implements Printer { // only what it can do
public void print(String doc) { System.out.println("Printing " + doc); }
}
class PrintQueue { // a client: needs printing only
void printAll(Printer p, String... docs) { for (String d : docs) p.print(d); }
}
public class Main {
public static void main(String[] args) {
PrintQueue q = new PrintQueue();
q.printAll(new HomePrinter(), "marksheet.pdf", "ticket.pdf");
q.printAll(new OfficeMachine(), "invoice.pdf");
Scanner s = new OfficeMachine();
s.scan("aadhaar-front.jpg");
}
}
Printing marksheet.pdf
Printing ticket.pdf
Printing invoice.pdf
Scanning aadhaar-front.jpg
- A class can implement many interfaces (episode 8).
HomePrinterhas no fake methods.PrintQueueasks for just aPrinter, so a change to scanning or faxing can't reach it.String... docsis a varargs parameter: the method accepts any number of strings as an array.- Adding stapling now means a new
Staplerinterface that onlyOfficeMachineimplements.HomePrinternever hears about it.
Note: our Scanner is our own interface. If you also import java.util.Scanner explicitly, the names clash; rename one (e.g. DocumentScanner).
The old bug can't be written any more
interface Printer { void print(String doc); }
interface Scanner { void scan(String doc); }
class HomePrinter implements Printer {
public void print(String doc) { System.out.println("Printing " + doc); }
}
public class Main {
static void scanAll(Scanner s) { s.scan("aadhaar-front.jpg"); }
public static void main(String[] args) {
scanAll(new HomePrinter());
}
}
Main.java:10: error: incompatible types: HomePrinter cannot be converted to Scanner
scanAll(new HomePrinter());
^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 error
The run-time crash became a compile error: the types tell the truth.
6. How to split an interface (and how not to)
- List the clients: who calls which methods?
- Group the methods that the same client uses together.
- One interface per group; the big class implements them all.
- Each client asks for the smallest interface it needs.
- Old code still uses the fat interface? Keep it as
interface Machine extends Printer, Scanner, Fax { }while you migrate callers (like episode 12's facade).
Step 5 in code, with a bonus: Printer has exactly one abstract method, so it is a functional interface and a lambda (episode 5) can implement it.
interface Printer { void print(String doc); }
interface Scanner { void scan(String doc); }
interface Fax { void fax(String doc, String number); }
interface Machine extends Printer, Scanner, Fax { } // old name, kept while migrating
class OfficeMachine implements Machine {
public void print(String doc) { System.out.println("Printing " + doc); }
public void scan(String doc) { System.out.println("Scanning " + doc); }
public void fax(String doc, String number) { System.out.println("Faxing " + doc); }
}
public class Main {
static void oldReport(Machine m) { m.print("old-report.pdf"); } // old caller, unchanged
static void printReceipt(Printer p) { p.print("receipt-42.pdf"); } // new caller
public static void main(String[] args) {
OfficeMachine office = new OfficeMachine();
oldReport(office);
printReceipt(office);
printReceipt(doc -> System.out.println("Thermal printer: " + doc));
}
}
Printing old-report.pdf
Printing receipt-42.pdf
Thermal printer: receipt-42.pdf
Old callers still compile against Machine; new callers ask for Printer. Small interfaces pay off twice: no fake methods, and they are easy to implement anywhere, even inline.
ISP and the other SOLID letters
- S: SRP splits classes by actor; ISP splits interfaces by client: the same idea one level up.
- O: a new role is a new interface, with no edits to old ones.
- L: fat interfaces force refused bequests (fake methods that throw).
Judge by clients, not by method count: a big interface is fine if every client really uses all of it.
Don't overdo it. One method per interface, everywhere, gives dozens of tiny types nobody can find. Split by client, not by method, just as SRP split by actor.
7. Marker interfaces
A marker interface has no methods at all; implementing it just tags a class with "yes". The JDK has a few: RandomAccess, Cloneable, Serializable.
RandomAccesstags lists that can reach any position fast (likeArrayList), so code can check it withinstanceofand choose a faster algorithm.CloneabletellsObject.clone()that copying is allowed. Cloning means making a field-by-field copy of an object.Serializabletags classes whose objects may be serialized: turned into bytes to save to a file or send over a network.
import java.util.*;
class Ticket { // forgot "implements Cloneable"
String seat = "S4-23";
public Ticket clone() throws CloneNotSupportedException { return (Ticket) super.clone(); }
}
class Pass implements Cloneable { // marker interface: no methods at all
String seat = "S4-24";
public Pass clone() throws CloneNotSupportedException { return (Pass) super.clone(); }
}
public class Main {
public static void main(String[] args) throws Exception {
System.out.println(new ArrayList<String>() instanceof RandomAccess);
System.out.println(new LinkedList<String>() instanceof RandomAccess);
System.out.println("Pass copy: " + new Pass().clone().seat);
System.out.println("Ticket copy: " + new Ticket().clone().seat);
}
}
true
false
Pass copy: S4-24
Exception in thread "main" java.lang.CloneNotSupportedException: Ticket
at java.base/java.lang.Object.clone(Native Method)
at Ticket.clone(Main.java:5)
at Main.main(Main.java:16)
A tag with no methods still changes behaviour.
Marker interface or annotation?
An annotation is extra information attached to code with @, read by the compiler or by tools (@Override, @FunctionalInterface).
| Marker interface | Annotation |
|---|---|
class Pass implements Cloneable |
@FunctionalInterface interface PaymentRule { ... } |
| It's a type: a method can demand it as a parameter, the compiler checks it | Information for tools and the compiler; not a type |
| Use it when you want the type check | Use it for metadata |
The class diagram
+---------------+ +---------------+ +--------------------+
| <<interface>> | | <<interface>> | | <<interface>> |
| Printer | | Scanner | | Fax |
| + print(doc) | | + scan(doc) | | + fax(doc, number) |
+---------------+ +---------------+ +--------------------+
^ ^ ^ uses ^ ^
| | '--- PrintQueue (depends on Printer only)
| '------------------ OfficeMachine (realizes all three) --'
'---- HomePrinter (realizes Printer only)
Common mistakes
| Mistake | Exact message | Why | Fix |
|---|---|---|---|
scan() { throw new UnsupportedOperationException(); } |
UnsupportedOperationException: No scanner |
A fat interface forced a fake method | Implement only the roles you have |
Adding staple() to Machine |
HomePrinter is not abstract and does not override abstract method staple(String) in Machine |
Every implementer must change | A new Stapler interface |
void printAll(Machine m, ...) |
no error: needless coupling | The client asks for more than it uses | Ask for Printer |
clone() on a class that isn't Cloneable |
CloneNotSupportedException: Ticket |
Missing marker interface | implements Cloneable (or a copy constructor) |
| One method per interface everywhere | no error: dozens of tiny types | Split by method, not by client | Group by client |
Mini project
The homework: split this fat interface. A Robot works but never eats or goes to the gym; a Manager works, eats, and attends the gym; a Canteen only feeds workers; a Payroll only cares about work hours.
interface Worker { void work(); void eat(); void attendGym(); }
Solution
interface Workable { String name(); int hours(); default void work() { System.out.println(name() + " works " + hours() + " h"); } }
interface Eater { void eat(); }
interface GymGoer { void attendGym(); }
class Manager implements Workable, Eater, GymGoer {
public String name() { return "Manager"; }
public int hours() { return 9; }
public void eat() { System.out.println("Manager eats lunch"); }
public void attendGym() { System.out.println("Manager attends gym"); }
}
class Robot implements Workable { // no fake eat() or attendGym()
public String name() { return "Robot"; }
public int hours() { return 24; }
}
class Canteen { void serve(Eater e) { e.eat(); } }
class Payroll { int totalHours(Workable... ws) { int t = 0; for (Workable w : ws) t += w.hours(); return t; } }
public class Main {
public static void main(String[] args) {
Manager m = new Manager();
Robot r = new Robot();
m.work(); r.work();
new Canteen().serve(m);
m.attendGym();
System.out.println("Payroll hours: " + new Payroll().totalHours(m, r));
}
}
Output:
Manager works 9 h
Robot works 24 h
Manager eats lunch
Manager attends gym
Payroll hours: 33
Each client (Canteen, Payroll) depends on one small role; Robot has no fake methods.
Practice
- Add a
Staplerrole to the role-interface version. Which existing classes change?
Solution
interface Printer { void print(String doc); }
interface Stapler { void staple(String doc); } // new role
class OfficeMachine implements Printer, Stapler { // the only class that changes
public void print(String doc) { System.out.println("Printing " + doc); }
public void staple(String doc) { System.out.println("Stapling " + doc); }
}
class HomePrinter implements Printer { // untouched, still compiles
public void print(String doc) { System.out.println("Printing " + doc); }
}
public class Main {
public static void main(String[] args) {
Stapler s = new OfficeMachine();
s.staple("report.pdf");
new HomePrinter().print("ticket.pdf");
}
}
Output:
Stapling report.pdf
Printing ticket.pdf
Only OfficeMachine changes. ISP and OCP together: a new role is a new interface, not an edit to a shared one.
Printerhas exactly one abstract method. WriteprintReceipt(Printer p)and call it with a lambda instead of a class.
Solution
@FunctionalInterface
interface Printer { void print(String doc); }
public class Main {
static void printReceipt(Printer p) { p.print("Receipt #42"); }
public static void main(String[] args) {
printReceipt(doc -> System.out.println("Thermal printer: " + doc));
printReceipt(doc -> System.out.println("PDF saved: " + doc));
}
}
Output:
Thermal printer: Receipt #42
PDF saved: Receipt #42
Small role interfaces are often functional interfaces (one abstract method), so lambdas can implement them: another payoff of keeping interfaces small.
- Keep old callers compiling while splitting
Machine. Write the transition interface.
Solution
interface Machine extends Printer, Scanner, Fax { } // old name, now just a union of roles
Old code that takes a Machine keeps working with OfficeMachine implements Machine; new code asks for Printer, Scanner or Fax. When no caller uses Machine, delete it.
- Is
java.util.List(about 30+ methods) a fat interface? Why don't we split it?
Solution
It's large, but nearly all of its clients use it as "a list" and many methods are convenience variations of the same role. Its real pain point is exactly what we saw last episode: optional operations like add that unmodifiable lists refuse. ISP is about clients being forced to depend on what they don't use; for most list clients, that isn't the case. Judge by clients, not by method count.
Quick quiz
interface Device { void print(String s); void scan(String s);
void fax(String s, String n); }
class Office implements Device { ... }
void printReceipt(??? d) { d.print("Receipt #42"); }
What should printReceipt take?
- A.
Device - B.
Object - C.
Printer(a new interface withprintonly) - D.
Office
Answer
C. printReceipt uses only print(). Asking for Printer lets any printer work and shields the method from scan/fax changes. Device drags in scan and fax, Office ties it to one product, and Object has no print method at all (it wouldn't compile).
Interview questions
- State the Interface Segregation Principle. No code should be forced to depend on methods it does not use; split fat interfaces into smaller, client-focused ones.
- Where does ISP come from? Robert C. Martin's consulting for Xerox: one fat
Jobclass used by every task made even small changes take about an hour to redeploy; he added one interface per job type. - What is a fat interface? Interface pollution? An interface with many methods serving many different clients; pollution is when it gains methods some implementers can't honour.
- What harm does a fat interface do even if nobody calls the unused methods? Implementers must write fake methods; every change to the interface forces every implementer and client to recompile or change.
- What is a role interface? A client-specific interface? A small interface for one role an object plays; an interface shaped by what one client needs.
- How do you split an interface? Group methods by the clients that use them, one interface per group, the big class implements all, clients ask for the smallest one, keep the old interface as
extends A, B, Cwhile migrating. - Can you over-apply ISP? Yes: one method per interface everywhere gives too many tiny types. Split by client, not by method.
- What is a marker interface? Give examples. An interface with no methods that tags a class:
Serializable,Cloneable,RandomAccess. - Marker interface vs annotation? A marker interface is a type the compiler can check in signatures; an annotation is metadata for the compiler and tools.
- How does ISP relate to LSP and SRP? Fat interfaces cause refused bequests (LSP violations); ISP applies SRP's "group by who changes it" idea to interfaces, grouping by client.
Glossary
| Term | Meaning, with an example |
|---|---|
| Interface Segregation Principle (ISP) | No code should be forced to depend on methods it does not use |
| Segregation | Separating. Splitting one interface into several |
| Interface | A list of methods a class promises to provide (episode 3) |
| Client | Code that uses an interface. PrintQueue uses Printer |
| Fat interface | Many methods serving many different clients. Machine with print, scan, fax, staple |
| Interface pollution | An interface gains methods some implementers can't honour |
| Fake method | A method written only to satisfy an interface; it throws or does nothing |
| Splitting interfaces | Turning one fat interface into several small ones, grouped by client |
| Role interface | A small interface for one role an object plays. Printer, Scanner |
| Client-specific interface | An interface shaped by what one client needs |
| Varargs | String... docs: a parameter that accepts any number of values as an array |
| Abstract method | A method with no body that implementers must provide |
| Marker interface | An interface with no methods that tags a class. Cloneable |
RandomAccess |
Marker for lists with fast access by position. ArrayList |
Cloneable |
Marker that allows Object.clone() |
| Cloning | Making a field-by-field copy of an object |
CloneNotSupportedException |
Thrown by clone() on a class that isn't Cloneable |
Serializable |
Marker for classes whose objects may be turned into bytes |
| Serialization | Turning an object into bytes to save or send it |
| Annotation | Extra information attached with @, read by the compiler or tools. @Override |
| Functional interface | An interface with exactly one abstract method; a lambda can implement it |
| Lambda | A short unnamed function (episode 5). doc -> System.out.println(doc) |
| Transition interface | The old fat interface kept as extends A, B, C while callers migrate |
Summary
- ISP: no code should be forced to depend on methods it does not use (Robert C. Martin, from the Xerox
Jobclass). - Fat interfaces force fake methods (
UnsupportedOperationException: No scanner) and spread every change (... does not override abstract method staple(String)). - Split into role interfaces; each client asks for the smallest client-specific interface it needs.
- Split by client, not by method; keep the old interface as
extends A, B, Cwhile migrating. - Marker interfaces (no methods) tag classes:
RandomAccess,Cloneable,Serializable.
Next episode: SOLID 5: Dependency Inversion and dependency injection.