ISP

ISP — Interface Segregation Principle

"Clients should not be forced to depend on methods they do not use." — Robert C. Martin, Agile Software Development

"Many client-specific interfaces are better than one general-purpose interface." — Uncle Bob's original wording


Core idea

Instead of one "fat" interface with 10 methods, use several narrow interfaces, each describing one role. A client depends only on the methods it actually calls. Nothing extra.


Why it matters

Fat interface Segregated interfaces
Implementations have to "pretend" to support methods they cannot do They implement only what they can do
Clients mock all methods, even the unused ones The mock is only the method that is needed
A change in one method triggers rebuilds in every client Clients are stable as long as their methods are stable
Tests become fragile: an error in fax() breaks the print() test Tests are isolated by role
An implementation with one or two real methods bloats into a 10-method class with stubs An honest class with exactly the methods it needs
LSP failures everywhere (through NotImplementedError) LSP holds naturally

ISP is preventive medicine for LSP failures. If the contract is narrow, it is easy to fulfil honestly.


Classic example: a multifunction device

❌ Fat interface

class MultifunctionDevice(Protocol):
    def print(self, doc: str) -> None: ...
    def scan(self, doc: str) -> str: ...
    def fax(self, doc: str, to: str) -> None: ...
    def copy(self) -> None: ...

"Every device must do all four". Now:

class SimplePrinter:
    def print(self, doc): print(f"printed: {doc}")
    def scan(self, doc): raise NotImplementedError("not a scanner")    # ❌ LSP!
    def fax(self, doc, to): raise NotImplementedError("no fax")        # ❌
    def copy(self): raise NotImplementedError("no copier")              # ❌

SimplePrinter is really just a printer. It was forced to "implement" scanning, fax, and copy through NotImplementedError. This is an LSP failure caused by a fat interface.

The client suffers too:

def print_report(device: MultifunctionDevice):
    device.print("report.pdf")

The function only uses print(), but it accepts a type with four methods. This means:

✅ Segregated interfaces

class Printer(Protocol):
    def print(self, doc: str) -> None: ...

class Scanner(Protocol):
    def scan(self, doc: str) -> str: ...

class Fax(Protocol):
    def fax(self, doc: str, to: str) -> None: ...

class Copier(Protocol):
    def copy(self) -> None: ...

Implementations are honest:

class SimplePrinter:                          # ← implements Printer only
    def print(self, doc): print(f"printed: {doc}")

class StandaloneScanner:                      # ← implements Scanner only
    def scan(self, doc): return f"scanned-{doc}"

class OfficeAllInOne:                         # ← implements all four roles
    def print(self, doc): print(f"printed: {doc}")
    def scan(self, doc): return f"scanned-{doc}"
    def fax(self, doc, to): print(f"faxed: {doc} → {to}")
    def copy(self): print("copied")

Clients accept exactly what they need:

def print_report(p: Printer):                # ← just a Printer
    p.print("report.pdf")

def digitize(s: Scanner) -> str:              # ← just a Scanner
    return s.scan("form-A")

print_report(SimplePrinter())                 # ✅
print_report(OfficeAllInOne())                # ✅ — satisfies Printer
digitize(StandaloneScanner())                 # ✅
digitize(OfficeAllInOne())                    # ✅

SimplePrinter does not have to pretend to be a scanner. print_report does not know about scanners or fax. Each class and each client has exactly as much contract as it needs.


Composing roles — one class fulfils several roles

OfficeAllInOne above is a natural composite: structurally it is Printer, Scanner, Fax, and Copier at the same time. No extends needed, Protocol checks by methods.

If you want to explicitly declare "this class is both a Printer and a Scanner", you can:

class PrintScanner(Printer, Scanner, Protocol):
    """Combined contract for a device that prints and scans."""
    ...

def process_office_task(device: PrintScanner):
    device.scan("doc")
    device.print("doc")

PrintScanner is a new Protocol that combines two. Any class that implements both methods is structurally compatible with PrintScanner. Composition of roles through types, no inheritance code.


ISP in real code: typical roles

from typing import Protocol, runtime_checkable

@runtime_checkable
class Readable(Protocol):
    def read(self) -> str: ...

@runtime_checkable
class Writable(Protocol):
    def write(self, data: str) -> None: ...

@runtime_checkable
class Closeable(Protocol):
    def close(self) -> None: ...

class Iterable(Protocol):                       # already in typing.Iterable
    def __iter__(self): ...

Each is tiny, each is about one thing. Classes that work with files can implement any combination:

class ReadOnlyFile:           # Readable + Closeable
    def read(self): ...
    def close(self): ...

class WriteOnlyLog:           # Writable + Closeable
    def write(self, data): ...
    def close(self): ...

class FullFile:               # Readable + Writable + Closeable
    def read(self): ...
    def write(self, data): ...
    def close(self): ...

Client functions ask for exactly what they need:

def parse_config(source: Readable) -> dict: ...
def log_event(sink: Writable, event: str) -> None: ...
def cleanup(closer: Closeable) -> None: ...

You can call cleanup(any_of_three) because all three are structurally Closeable.


How to spot an ISP violation

1. Implementations with raise NotImplementedError or pass in required methods

class CsvReader(DataSource):
    def read(self): ...
    def write(self, data): pass    # ← "we do not use it", but had to implement

pass is worse than NotImplementedError — it silently does nothing instead of failing loudly. A classic symptom of a fat interface.

2. The client uses one or two of ten methods

def export(printer: MultifunctionDevice):
    printer.print("doc")           # ← all that is used
    # scan, fax, copy are not used, but the client depends on them

3. Mocks in tests need to implement methods the test does not touch

If your Mock(spec=BigInterface) has ten methods but the test calls one, the interface is fat.

4. The interface grows with every new feature

Every new requirement adds a method to the shared interface. That is the God Interface anti-pattern.


ISP and Python specifics

Python is especially friendly to ISP

Python has no "one class per Protocol" restriction. A class structurally is anything it matches:

class File:
    def read(self): ...
    def write(self, x): ...
    def close(self): ...

f = File()
isinstance(f, Readable)    # True (with @runtime_checkable)
isinstance(f, Writable)    # True
isinstance(f, Closeable)   # True

This is exactly what Java and C# try to achieve through "implements I1, I2, I3", and Python has it built in. Use it.

Python's standard Protocols are already segregated

typing gives you narrow ones: Iterable, Iterator, Sized, Hashable, Container. collections.abc has the same as ABCs.

That is not an accident — the standard library itself follows ISP. Remember this pattern:

def first(items: Iterable[T]) -> T:      # I only need __iter__
    return next(iter(items))

def length(c: Sized) -> int:              # I only need __len__
    return len(c)

Anti-patterns

1. "A base class with everything"

class BaseRepository(ABC):
    @abstractmethod
    def save(self, item): ...
    @abstractmethod
    def load(self, id): ...
    @abstractmethod
    def delete(self, id): ...
    @abstractmethod
    def search(self, query): ...
    @abstractmethod
    def count(self): ...
    @abstractmethod
    def bulk_insert(self, items): ...
    @abstractmethod
    def transaction(self): ...

Seven methods — any subclass has to implement all of them. A read-only repo? Does not exist. An in-memory cache without transactions? Stubs.

Refactor: separate ReadRepository, WriteRepository, SearchableRepository, Transactional.

2. Passing "anything" as Any

def process(data: Any):                  # ← no contract at all
    ...

This is the other extreme: no ISP, not because the interface is fat, but because it is missing. Without a contract you cannot test or refactor.

ISP is about getting the contract the right size.

3. A "bare" Protocol that mirrors every method of the class

class IUserService(Protocol):           # duplicates every UserService method
    def register(self, ...): ...
    def login(self, ...): ...
    def reset_password(self, ...): ...
    def export_to_csv(self, ...): ...
    ...

If your Protocol repeats every implementation method, it is not segregated. ISP asks for role-shaped Protocols, not a "copy of the class".

4. Segregation for the sake of segregation

class CanSave(Protocol):
    def save(self): ...

class CanSaveOne(Protocol):
    def save_one(self, x): ...

class CanSaveMany(Protocol):
    def save_many(self, xs): ...

Three Protocols for three variants of one method is over-engineering. ISP does not call for infinite splitting. Extract a Protocol where it has a real client.


Relationship to other principles

Principle How ISP relates
LSP Narrow interfaces are easier to fulfil honestly, fewer NotImplementedError
SRP An interface with one role = one axis of change = SRP at the contract level
OCP Small Protocols are easier to extend (a new combination is enough)
DIP Depending on a narrow abstraction is exactly what DIP requires
Composition over inheritance A class structurally fulfils N roles, no multiple inheritance needed

Rules of thumb

  1. Each Protocol is about one role. If the name contains "and", split it.
  2. Implementations with stubs are a fat-interface signal. pass or NotImplementedError inside an override is an ISP failure.
  3. The client is typed by exactly what it uses. If it calls .read(), accept Readable, not File.
  4. Compose Protocols through Protocol-inheritance (class ReadWrite(Read, Write, Protocol): ...).
  5. Do not extract a Protocol for one client and one implementation. YAGNI. Wait until there is a second implementation or a test mock.
  6. Prefer the narrow Protocols from the standard library (Iterable, Sized, Hashable). Everyone knows them.
  7. One class can implement many Protocols, and that is fine. That is "playing several roles".

One-line summary

Small role-shaped Protocols instead of one big "everything" interface. The client depends on exactly what it needs, nothing more.