Skip to content

Interface Segregation Principle (ISP) ​

"Clients should not be forced to depend upon interfaces that they do not use." — Robert C. Martin, The Interface Segregation Principle, The C++ Report, 1996

Summary: ISP says an interface should be shaped by what one kind of client needs, so no client pays for methods it never calls and no implementation has to fake methods it cannot honour. Focus: Interface pollution and fat interfaces, role vs header interfaces, client-specific and consumer-defined interfaces (Go), composition, optional capability and marker interfaces, Laravel and PSR contracts, and ISP at system level (BFF, GraphQL, events, read models). Learning goal: Read an interface and its call sites, name the roles hiding in it, split it without over-segregating, and apply the same test to APIs, events and database access.

This page is the complete reference for the I in SOLID: the 1996 origin (Martin's door and timer), every term practitioners use around it (interface pollution, fat interface, role interface, header interface, client-specific interface, marker interface, optional interface, over-segregation), how Go, PHP/Laravel, Java, C#, TypeScript and Python express segregated interfaces, the real Laravel and PSR contracts that show it done well, and how the principle reappears as Backend for Frontend, GraphQL field selection, fine-grained events and per-client database views. Neighbours: a fat interface usually forces implementations to lie, which is a Liskov violation; who owns each small interface is Dependency Inversion; keeping one reason to change per module is Single Responsibility. The SOLID overview is at /design/solid/.

Page map ​

If you are looking forGo to
The principle in tablesEverything in one minute
Why it exists, the trade-offWhy ISP exists
Martin's door and timer, Fowler, Pike, CheneyWhere it comes from
Fat interface, role vs header, client-specific, composition, optional and marker interfaces, over-segregationThe concepts, one by one
How each language and framework expresses itPer-language behaviour
Go and Laravel before/after codeGo, Laravel
Change propagation, recompilation, mocks, method countsMechanics
Splitting a repository, a notifier, an SDK wrapper, a God serviceSolving the classic problems
When to split and when to stopChoosing
BFF, GraphQL, events, read models, database viewsIn architecture
Refactoring kata with real outputLab
Wrong beliefs, cheat sheet, termsMisconceptions, Cheat sheet, Glossary

Everything in one minute ​

The vocabulary.

TermIn plain wordsTiny exampleGood or bad
Fat interfaceOne interface serving several kinds of clientsDoor with Lock, Unlock, IsOpen, TimeOutBad when clients differ
Interface pollutionA method added to a shared interface for one implementation's benefitTimeOut added to Door for TimedDoorBad
Header interfaceAn interface that copies a class's whole public APIUserServiceInterface with all 25 methodsUsually bad
Role interfaceAn interface shaped by one collaborationTimerClient { TimeOut() }Good
Client-specific interfaceDefined from the client's point of viewOtpService needs SendsSmsGood
Consumer-defined interface (Go)Declared in the package that uses ittype orderMarker interface{ MarkPaid(...) } in checkoutGood
Optional capability interfaceExtra interface an implementation may addfs.ReadFileFS, Laravel LockProviderGood if the base is complete
Marker interfaceInterface with no methods, read as a flagLaravel ShouldQueueFine, use sparingly
Over-segregationSo many tiny interfaces that nothing is cohesiveHasId, HasName, HasEmail for one entityBad

The test.

QuestionIf yes
Do different callers use disjoint subsets of the methods?Split by caller
Does any implementation stub, no-op or throw for a method?Split; it is also an LSP violation
Does a change to method A force retesting or redeploying clients that only use B?Split
Would the split interfaces each have a single, nameable role?Split along those names
Does every client use every method?Do not split (sort.Interface has three methods and one client)

The three things to do.

SituationDo this
Writing a function or classAccept the smallest interface that names what you use
Writing an implementationReturn the concrete type; let consumers define the interfaces they need
Designing an API or eventShape it per client (BFF, GraphQL selection, fine-grained events)

Why ISP exists ​

Every method on an interface you depend on is a reason you might have to change, even if you never call it. Martin's 1996 argument: when clients depend on interfaces they do not use, "then those clients are subject to changes to those interfaces. This results in an inadvertent coupling between all the clients." In C++ that coupling meant recompiling and redeploying; in every language it means reading, mocking, versioning and retesting code that has nothing to do with you. The opposite cost is real too: many tiny interfaces are harder to find and name.

One wide interfaceSeveral role interfaces
One name to learn, easy to discoverSeveral names, each meaningful to its client
Every client couples to every methodEach client couples to what it uses
Fakes must implement everythingFakes implement one or two methods
Implementations stub what they cannot doImplementations implement only what they do
A change ripples to all clientsA change touches only the role's clients
Fine when all clients use everythingOverkill when there is only one client

The analogy we reuse on this page: a television remote. A sixty-button remote is a fat interface: every viewer depends on all sixty, must learn to ignore most of them, and every redesign of the rarely used buttons risks moving the volume control. A hotel remote with power, volume and channel is a role interface for guests; the technician's service remote is another role interface for another client. The television did not change. The interface was shaped to the client.

Three common misunderstandings, up front ​

  1. "Every interface should have one method." The test is per-client cohesion, not a count. sort.Interface has three methods and is perfectly segregated because its only client, sort.Sort, needs all three.
  2. "ISP is a compile-time C++ concern." The recompilation argument is dated; the coupling is not. Fakes, mocks, documentation, versioning and the forced-stub lie are costs in Go, PHP and TypeScript.
  3. "Split the implementation into many classes." ISP splits interfaces. One class may implement several role interfaces (Martin's TimedDoor implements Door and TimerClient); clients just see the role they need.

Where it comes from ​

Martin, 1996. ISP is the fourth Engineering Notebook column in The C++ Report. Martin calls the problem interface pollution and introduces it with a security system: "Consider a security system. In this system there are Door objects that can be locked and unlocked, and which know whether they are open or closed." TimedDoor must sound an alarm when left open too long, so it registers with a Timer that calls back TimerClient::TimeOut. The quick fix is to make Door inherit from TimerClient. His verdict:

"The interface of Door has been polluted with an interface that it does not require. It has been forced to incorporate this interface solely for the benefit of one of its subclasses." — Robert C. Martin, The Interface Segregation Principle, 1996

His remedy is a slogan of its own, "Separate Clients mean Separate Interfaces": Door and TimerClient "represent interfaces that are used by completely different clients", so TimedDoor should implement both, through multiple inheritance or delegation (an adapter object). A widely repeated story places the origin in consulting work for Xerox on a printer system; that account is from secondary sources (Wikipedia and talks), and the 1996 column itself uses only the door example.

Fowler, role and header interfaces. Martin Fowler's bliki (2006) names the two styles. A header interface "is an explicit interface that mimics the implicit public interface of a class". A role interface is the opposite:

"A role interface is defined by looking at a specific interaction between suppliers and consumers. A supplier component will usually implement several role interfaces, one for each of these patterns of interaction." — Martin Fowler, RoleInterface, bliki

He ties it back explicitly: "role interfaces follow that principle but header interfaces do not", and names the cost of role interfaces honestly: they are "more effort to come up with, since you need to look at each collaboration".

Go, the proverb. Rob Pike's Go Proverbs (Gopherfest 2015) put it in six words: "The bigger the interface, the weaker the abstraction." The Go wiki's Code Review Comments turn it into a rule of placement: "Go interfaces generally belong in the package that uses values of the interface type, not the package that implements those values." Cheney's SOLID Go Design adds the idiom "accept interfaces, return structs" and notes "the prevailing idiom is an interface contains only a single method".

PanelTimerAuditfat Door interfaceLock · Unlock · IsOpenTimeOut · AuditTrailevery client sees all fiveTimedDoorall realPlainDoorTimeOut() { } stubBefore: interface pollutionPanelTimerAuditDoor3 methodsTimerClientTimeOutAuditableAuditTrailTimedDoorDoor+TimerClient+AuditablePlainDoorDoor onlyAfter: role interfaces per client

On the left of the diagram, three different clients all see one fat Door, and PlainDoor has to stub TimeOut. On the right, each client sees one role interface, and each door implements exactly the roles it really plays.

The concepts, one by one ​

Fat interface and interface pollution Must-know ​

In plain words: an interface becomes fat when methods for different kinds of clients pile up in it, often because adding one more method to the existing interface was the easiest change.

Common misunderstanding: "A big interface is fine as long as each method is cohesive with the domain." Domain cohesion is not the test; client cohesion is. UserRepository can be perfectly "about users" and still serve a login screen, a reporting job and an admin console that share nothing.

Definition: Martin: classes with "fat" interfaces "are classes whose interfaces are not cohesive", where cohesion is measured by which clients use which groups of methods. Interface pollution is the act that creates them: putting a method into a shared interface "solely for the benefit of one of its subclasses".

text
     Change request                                  Who is affected
1    TimerClient.TimeOut gains a timer id parameter  TimedDoor (needs it)
2    Door embeds TimerClient                         PlainDoor, SlidingDoor, VaultDoor must change
3                                                    SecurityPanel (uses only Lock/Unlock) recompiles, retests, redeploys
4    -- one client's need rippled to every client of Door

Real scenarios: a NotificationChannel with sendEmail, sendSms, sendPush that every channel must implement; a PaymentGateway with charge, refund, payout, kycCheck where most providers support only two; a 40-method UserService that every controller injects; a Go Storage interface with Get, Put, List, Watch, Lock, Snapshot because the first implementation (etcd) had them all.

Fix: list the clients, list the methods each one calls, and split along the groups. Code in Go and Laravel.

Role interface vs header interface Must-know ​

In plain words: a header interface copies what a class has; a role interface describes what a client needs.

Common misunderstanding: "Extracting an interface from my class (the IDE's 'Extract Interface' on all methods) is good design." It produces a header interface: every client now depends on every method, and the interface changes whenever the class does.

Definition: Fowler: a role interface is "defined by looking at a specific interaction between suppliers and consumers"; a header interface "mimics the implicit public interface of a class". A supplier typically implements several role interfaces.

text
     Header style                                    Role style
1    interface UserServiceInterface { 25 methods }   interface FindsUserByEmail { findByEmail() }
2    LoginController(UserServiceInterface $s)        LoginController(FindsUserByEmail $users)
3    test fake implements 25 methods                 test fake implements 1 method
4    rename exportCsv() -> every fake changes        rename exportCsv() -> only ReportJob's role changes

Real scenarios: C#/Java codebases with IFooService for every FooService "for mocking"; PHP projects with App\Contracts\XInterface mirroring every service; Go packages that export type Client interface { ...all methods... } next to type client struct.

Fix: start from call sites, not from the class. Name roles after what the client does with them (TimerClient, FindsUserByEmail, io.Writer).

Client-specific and consumer-defined interfaces Must-know ​

In plain words: the interface lives with, and is named by, the code that uses it. In Go this is the norm because interfaces are satisfied implicitly: the implementing package does not even need to know.

Common misunderstanding: "The package that implements a thing should export its interface so others can mock it." The Go wiki says the opposite: "Do not define interfaces on the implementor side of an API 'for mocking'; instead, design the API so that it can be tested using the public API of the real implementation."

Definition: a client-specific interface contains exactly the methods one client (or one kind of client) calls. Go's guideline: interfaces "generally belong in the package that uses values of the interface type", and the implementing package "should return concrete (usually pointer or struct) types: that way, new methods can be added to implementations without requiring extensive refactoring." This is the idiom accept interfaces, return structs.

text
     package checkout                               package postgres
1    type orderMarker interface {                   type OrderRepo struct{...}
       MarkPaid(ctx, id) error }                    func (r *OrderRepo) MarkPaid(...) error
                                                    func (r *OrderRepo) Find(...) ...
                                                    func (r *OrderRepo) ListForAdmin(...) ...
2    func NewService(m orderMarker) *Service        -- postgres never imports checkout
3    main: checkout.NewService(postgres.New(db))    -- *OrderRepo satisfies orderMarker implicitly

Real scenarios: an OtpService that needs only SendsSms; a Go handler that needs only interface{ GetUser(ctx, id) (User, error) }; a report job that needs iterable<Order> rather than the whole repository; Cheney's Save(w io.Writer, doc *Document).

LanguageWhere client-specific interfaces naturally liveImplementer must declare it?
GoConsumer package, often unexportedNo (implicit satisfaction)
PHP / LaravelApp\Contracts or the consuming moduleYes (implements)
JavaConsumer module (or a separate API module)Yes
C#Consumer assemblyYes
TypeScriptAnywhere; Pick<T, 'a' | 'b'> derives one from a class typeNo (structural)
Pythontyping.Protocol in the consumer moduleNo (structural, checked by mypy/pyright)

Fix: narrow every parameter to the smallest interface that names the behaviour used. Cheney's walk-through: from *os.File to io.ReadWriteCloser to io.Writer, after which Save "has simultaneously been a function which is the most specific in terms of its requirements, it only needs a thing that is writable, and the most general in its function".

Composition of small interfaces Important ​

In plain words: when a client genuinely needs several roles, combine small interfaces instead of writing a big one.

Common misunderstanding: "If I split interfaces, clients that need two of them must take two parameters." They can take one parameter of a composed interface.

Definition: Go embeds interfaces in interfaces (type ReadWriteCloser interface { Reader; Writer; Closer }); PHP and Java let an interface extend several (interface ReadWrite extends Reads, Writes); TypeScript uses intersections (Reader & Writer); Python composes Protocol classes.

text
1    io.Copy(dst Writer, src Reader)                  -- needs two roles, takes two small params
2    gzip.NewWriter(w io.Writer)                      -- wraps any Writer
3    func Pipe(rw io.ReadWriteCloser)                 -- a client that truly needs three roles
4    *os.File, net.Conn, *gzip.Reader+Writer pairs    -- each satisfies exactly what it can

Real scenarios: io.ReadWriteCloser, io.ReadSeeker, http.ResponseWriter + optional http.Flusher; Laravel's Illuminate\Contracts\Cache\Repository extending PSR-16's Psr\SimpleCache\CacheInterface; Java's Deque extending Queue.

Fix: keep the atoms small and compose at the call site that needs more.

Optional capability interfaces Important ​

In plain words: a small base interface everyone implements, plus extra interfaces some implementations add for extra abilities or speed. Clients check for the extra and fall back if it is absent.

Common misunderstanding: "A type assertion to another interface is the same smell as instanceof." It is not, when the base contract is complete without the extra and the client has a correct fallback.

Definition: Go's io/fs documents the pattern: "The FS interface is the minimum implementation required of the file system. A file system may implement additional interfaces, such as [ReadFileFS], to provide additional or optimized functionality." fs.ReadFile uses ReadFileFS when present and Open + Read otherwise.

text
     fs.ReadFile(fsys, "doc.json")
1    if rf, ok := fsys.(fs.ReadFileFS); ok -> rf.ReadFile(name)   -- fast path
2    else f := fsys.Open(name); io.ReadAll(f)                       -- base contract
     Laravel Cache::lock('report')
3    if (! $store instanceof LockProvider) throw BadMethodCallException('This cache store does not support locks.')

Real scenarios: io.WriterTo/io.ReaderFrom used by io.Copy to avoid a buffer; http.Flusher and http.Hijacker on a ResponseWriter; Laravel's LockProvider (memcached, redis, dynamodb, database, file, array stores) and CanFlushLocks; PSR-18 clients that may also implement async interfaces of their library.

Optional interfaceBase interfaceFallback when absent
Go fs.ReadFileFS, fs.StatFS, fs.ReadDirFSfs.FSOpen and read/stat through the file
Go io.WriterTo, io.ReaderFromio.Reader, io.Writerio.Copy uses a buffer
Go http.Flusherhttp.ResponseWriterNo streaming; response is buffered
Laravel Illuminate\Contracts\Cache\LockProviderIlluminate\Contracts\Cache\StoreBadMethodCallException (no silent fallback)

Fix: make the base interface sufficient; add capabilities as separate, documented interfaces; keep the fallback correct.

Marker interfaces Good to know ​

In plain words: an interface with no methods, used as a label that one part of the framework reads.

Common misunderstanding: "An empty interface is pointless." In Laravel it is a precise, opt-in contract with exactly one reader; in Go, by contrast, the empty interface any "says nothing" (Pike) because every type satisfies it.

Definition: a marker interface carries meaning through instanceof checks rather than methods. Laravel's queue system uses several: Illuminate\Contracts\Queue\ShouldQueue (the job or listener is pushed onto the queue), ShouldBeUnique, ShouldBeUniqueUntilProcessing, ShouldBeEncrypted; the queue documentation says a generated job "will implement the Illuminate\Contracts\Queue\ShouldQueue interface, indicating to Laravel that the job should be pushed onto the queue to run asynchronously."

text
1    class SendInvoice implements ShouldQueue                  -- marker: "run me async"
2    event(new OrderPlaced) -> listener implements ShouldQueue -- dispatcher queues it instead of calling it
3    class RebuildIndex implements ShouldQueue, ShouldBeUnique -- second marker read by a different component

Real scenarios: Laravel ShouldQueue on jobs, listeners, mailables and notifications; ShouldBroadcast on events; Java's Serializable and Cloneable (the latter famous for not working well as a marker); Go uses unexported marker methods instead (isExpr()) to close a sum type.

Fix: use a marker only when exactly one component reads it and no behaviour is needed; prefer attributes (PHP 8) or explicit configuration otherwise.

Segregation vs cohesion, and over-segregation Important ​

In plain words: split until each interface has one kind of client, then stop. Splitting further fragments a cohesive role into pieces nobody uses alone.

Common misunderstanding: "More, smaller interfaces are always better." One-method interfaces for every getter (HasId, HasName, HasEmail) produce long parameter type lists, hard-to-find code and interfaces whose only client is a test.

Definition: an interface is well segregated when its methods are used together by its clients. That is cohesion measured from the client side. Over-segregation is when methods that every client always uses together are split anyway.

text
     Over-segregated                                      Right-sized
1    func Sort(l Lenner, s Swapper, c LessComparer)       func Sort(data sort.Interface)
2    -- three params, always the same object               -- one role: "sortable collection"
3    PSR-3 LoggerInterface: 8 level methods + log()        -- one client role ("logger"), cohesive despite 9 methods

Real scenarios: sort.Interface (three methods, one role); PSR-3's LoggerInterface (nine methods, all "log at level X", one role); PSR-11's ContainerInterface (get and has, one role); an interface per CRUD verb for an entity no client reads without writing.

Fix: group by client use. If every caller always needs A and B together, they belong in one interface; if no caller ever needs them together, they belong in two.

Per-language behaviour ​

CapabilityGoPHP / LaravelJavaC#TypeScriptPython
Interfaces satisfiedImplicitly (structural)Explicitly (implements)ExplicitlyExplicitlyStructurallyNominal (ABC) or structural (Protocol)
Define role after the fact (no change to implementer)YesNo (adapter needed)No (adapter)No (adapter)YesYes with Protocol
Compose interfacesEmbeddinginterface A extends B, Cextends B, C: IB, ICA & B, extendsMultiple Protocol bases
Derive a narrow view of a classDeclare a small interfaceDeclare a small interfaceSameSamePick<Class, 'm1' | 'm2'>Protocol with the used methods
Default methods on interfacesNoNo (traits instead)Yes (Java 8+)Yes (C# 8+)NoYes (ABC/Protocol bodies)
Optional capability checkType assertion v.(I)instanceofinstanceofis / asType guardisinstance with runtime_checkable
Marker interfaces commonNo (prefer unexported methods)Yes (ShouldQueue)Yes (Serializable)Rare (attributes)NoRare
Framework / standardSegregated contracts it ships
Go stdlibio.Reader, io.Writer, io.Closer, io.Seeker, composed io.ReadWriteCloser; fmt.Stringer; http.Handler (one method); fs.FS + ReadFileFS/StatFS/ReadDirFS/GlobFS/SubFS
Laravel 13Authenticatable, CanResetPassword, MustVerifyEmail, Authorizable; cache Store vs Repository vs LockProvider; ShouldQueue, ShouldBeUnique, ShouldBeEncrypted
PHP-FIG PSRsPSR-3 LoggerInterface; PSR-7 separate RequestInterface, ServerRequestInterface, ResponseInterface, StreamInterface, UriInterface; PSR-11 ContainerInterface (get, has); PSR-14 dispatcher vs listener provider; PSR-16 simple cache; PSR-18 ClientInterface (one method, sendRequest)
JavaIterable → Collection → List; AutoCloseable; Comparable
.NETIEnumerable<T>, IReadOnlyCollection<T>, IReadOnlyList<T> alongside IList<T>; IDisposable
NestJS / SpringLifecycle hooks as separate interfaces: OnModuleInit, OnModuleDestroy (NestJS); InitializingBean, DisposableBean (Spring)

Go ​

Before ​

Martin's door, in Go. TimeOut has been added to Door because one implementation needed it. PlainDoor is now forced to carry a method it cannot honour.

go
package before

// Door started life with three methods. Then TimedDoor needed a timer callback,
// and the easiest fix was to add TimeOut to the Door interface itself.
type Door interface {
	Lock()
	Unlock()
	IsOpen() bool
	TimeOut() // only one implementation ever needs this
}

type TimedDoor struct {
	open, locked bool
}

func (d *TimedDoor) Lock()        { d.locked = true }
func (d *TimedDoor) Unlock()      { d.locked = false }
func (d *TimedDoor) IsOpen() bool { return d.open }
func (d *TimedDoor) TimeOut()     { /* sound the alarm */ }

// PlainDoor has no timer, but it is forced to carry a method it cannot honour.
type PlainDoor struct {
	open, locked bool
}

func (d *PlainDoor) Lock()        { d.locked = true }
func (d *PlainDoor) Unlock()      { d.locked = false }
func (d *PlainDoor) IsOpen() bool { return d.open }
func (d *PlainDoor) TimeOut()     { /* nothing sensible to do here */ }

After ​

Two interfaces for two clients. TimedDoor satisfies both because it really does both jobs. PlainDoor satisfies only Door, and the compiler never asks it to pretend.

go
package after

import "time"

// Door is what the security system needs. Nothing more.
type Door interface {
	Lock()
	Unlock()
	IsOpen() bool
}

// TimerClient is what the Timer needs. A different client, a different interface.
type TimerClient interface {
	TimeOut()
}

type Timer struct{}

func (Timer) Register(after time.Duration, c TimerClient) {
	time.AfterFunc(after, c.TimeOut)
}

// TimedDoor satisfies both interfaces because it genuinely does both jobs.
type TimedDoor struct {
	open, locked bool
}

func (d *TimedDoor) Lock()        { d.locked = true }
func (d *TimedDoor) Unlock()      { d.locked = false }
func (d *TimedDoor) IsOpen() bool { return d.open }
func (d *TimedDoor) TimeOut()     { /* sound the alarm */ }

// PlainDoor satisfies only Door. No empty methods, no lies.
type PlainDoor struct {
	open, locked bool
}

func (d *PlainDoor) Lock()        { d.locked = true }
func (d *PlainDoor) Unlock()      { d.locked = false }
func (d *PlainDoor) IsOpen() bool { return d.open }

Narrowing parameters: io.Writer and fs.FS ​

Cheney's Save, plus a Load that accepts any read-only file system and benefits from the optional fs.ReadFileFS capability through fs.ReadFile.

go
// Package save is Cheney's ISP example: narrow the parameter until it
// names only the behaviour the function uses.
package save

import (
	"encoding/json"
	"io"
	"io/fs"
)

type Document struct {
	Title string `json:"title"`
	Body  string `json:"body"`
}

// Save needs only to write. Files, sockets, buffers, gzip writers and
// http.ResponseWriter all qualify; tests pass a *bytes.Buffer.
func Save(w io.Writer, doc *Document) error {
	return json.NewEncoder(w).Encode(doc)
}

// Load needs only a read-only file system. fs.ReadFile uses the optional
// fs.ReadFileFS capability when the implementation offers it and falls back
// to Open + Read otherwise: a small base interface plus opt-in extras.
func Load(fsys fs.FS, name string) (*Document, error) {
	b, err := fs.ReadFile(fsys, name)
	if err != nil {
		return nil, err
	}
	var d Document
	return &d, json.Unmarshal(b, &d)
}

A consumer-defined interface ​

The interface is declared next to its client, unexported, with only the methods the client calls. The concrete repository may have twenty methods; this package depends on one.

go
package checkout

import "context"

// orderMarker is the role checkout needs. *postgres.OrderRepo satisfies it
// without importing this package.
type orderMarker interface {
	MarkPaid(ctx context.Context, id string) error
}

type Service struct{ orders orderMarker }

func NewService(orders orderMarker) *Service { return &Service{orders: orders} }

// In tests, a one-line fake is enough:
type fakeMarker struct{ ids []string }

func (f *fakeMarker) MarkPaid(_ context.Context, id string) error {
	f.ids = append(f.ids, id)
	return nil
}

The Go angle ​

Go is the language where ISP became idiom. Implicit satisfaction means the client can declare the role after the fact, without touching the implementer, so interfaces naturally shrink to what each client uses; the standard library is built on one-method interfaces (io.Reader, io.Writer, io.Closer, fmt.Stringer, http.Handler, error) composed when needed (io.ReadWriteCloser). Pike's proverb, "The bigger the interface, the weaker the abstraction", and its companion "interface{} says nothing" mark the two ends. The Go wiki adds two rules worth memorising: define interfaces where they are used, and "Do not define interfaces before they are used". The accepted exception to "small" is sort.Interface: three methods, one client that needs all three. Watch for the Go-specific fat interface: an exported Client interface in an SDK package that mirrors every method of the concrete client "for mocking"; return the struct and let consumers declare roles.

Laravel ​

Before ​

A NotificationChannel interface that bundles email, SMS and push. An SMS provider must implement sendEmail and sendPush and has nothing honest to put in them.

php
<?php

namespace App\Contracts;

use App\Models\User;

// One interface for every way a message could leave the system.
// Every channel must implement all three, whether it can or not.
interface NotificationChannel
{
    public function sendEmail(User $user, string $subject, string $body): void;

    public function sendSms(User $user, string $text): void;

    public function sendPush(User $user, string $title, string $body): void;
}

namespace App\Channels;

use App\Contracts\NotificationChannel;
use App\Models\User;
use LogicException;

final class SmsChannel implements NotificationChannel
{
    public function sendSms(User $user, string $text): void
    {
        // call the SMS provider
    }

    public function sendEmail(User $user, string $subject, string $body): void
    {
        throw new LogicException('SMS channel cannot send email'); // forced to lie
    }

    public function sendPush(User $user, string $title, string $body): void
    {
        throw new LogicException('SMS channel cannot send push'); // forced to lie
    }
}

After ​

One interface per client need. OtpService depends on SendsSms and nothing else, so it can be tested with a two-line fake and is untouched when the email contract changes.

php
<?php

namespace App\Contracts;

use App\Models\User;

// One interface per client need. A channel implements only what it does.
interface SendsSms
{
    public function sendSms(User $user, string $text): void;
}

interface SendsEmail
{
    public function sendEmail(User $user, string $subject, string $body): void;
}

interface SendsPush
{
    public function sendPush(User $user, string $title, string $body): void;
}

namespace App\Channels;

use App\Contracts\SendsEmail;
use App\Contracts\SendsSms;
use App\Models\User;

final class SmsChannel implements SendsSms
{
    public function sendSms(User $user, string $text): void
    {
        // call the SMS provider
    }
}

// A channel that genuinely does two jobs implements two small interfaces.
final class TwilioChannel implements SendsSms, SendsEmail
{
    public function sendSms(User $user, string $text): void {}

    public function sendEmail(User $user, string $subject, string $body): void {}
}

// The client asks for exactly what it needs and nothing else.
namespace App\Services;

use App\Contracts\SendsSms;
use App\Models\User;

final class OtpService
{
    public function __construct(private SendsSms $sms) {}

    public function send(User $user, string $code): void
    {
        $this->sms->sendSms($user, "Your code is {$code}");
    }
}

Splitting a repository by role ​

A header-style UserRepository serves the login controller, the admin console and a nightly report. Each gets a role interface; one Eloquent class implements all three, and the container binds each role to it.

php
<?php

namespace App\Users\Contracts;

use App\Models\User;

interface FindsUsersByEmail
{
    public function findByEmail(string $email): ?User;
}

interface ManagesUsers
{
    public function suspend(int $id, string $reason): void;
    public function reinstate(int $id): void;
}

interface StreamsUsersForReports
{
    /** @return iterable<User> */
    public function activeSince(\DateTimeInterface $since): iterable;
}

namespace App\Users;

use App\Models\User;
use App\Users\Contracts\{FindsUsersByEmail, ManagesUsers, StreamsUsersForReports};

final class EloquentUsers implements FindsUsersByEmail, ManagesUsers, StreamsUsersForReports
{
    public function findByEmail(string $email): ?User
    {
        return User::where('email', $email)->first();
    }

    public function suspend(int $id, string $reason): void
    {
        User::whereKey($id)->update(['suspended_at' => now(), 'suspension_reason' => $reason]);
    }

    public function reinstate(int $id): void
    {
        User::whereKey($id)->update(['suspended_at' => null, 'suspension_reason' => null]);
    }

    public function activeSince(\DateTimeInterface $since): iterable
    {
        return User::where('last_seen_at', '>=', $since)->lazyById(1000);
    }
}

// AppServiceProvider::register(): one implementation, three roles.
//   $this->app->singleton(EloquentUsers::class);
//   $this->app->bind(FindsUsersByEmail::class, EloquentUsers::class);
//   $this->app->bind(ManagesUsers::class, EloquentUsers::class);
//   $this->app->bind(StreamsUsersForReports::class, EloquentUsers::class);

The Laravel angle ​

Laravel's authentication contracts are a textbook segregation by client. Illuminate\Contracts\Auth\Authenticatable is what guards and user providers need; Illuminate\Contracts\Auth\CanResetPassword is what the password broker needs; Illuminate\Contracts\Auth\MustVerifyEmail is what the verification middleware and listener need; Illuminate\Contracts\Auth\Access\Authorizable is what the gate needs. The framework's base Illuminate\Foundation\Auth\User implements AuthenticatableContract, AuthorizableContract and CanResetPasswordContract, and MustVerifyEmail is opt-in: the verification docs tell you to "verify that your App\Models\User model implements the Illuminate\Contracts\Auth\MustVerifyEmail contract" only when you turn verification on. The cache is split the same way: Illuminate\Contracts\Cache\Store is what a driver must provide, Illuminate\Contracts\Cache\Repository is what application code uses, and LockProvider is an optional capability. Queue behaviour is opted into with marker interfaces (ShouldQueue, ShouldBeUnique, ShouldBeEncrypted). In application code, the anti-pattern to look for is a FooServiceInterface that mirrors FooService method for method and is injected everywhere.

Mechanics ​

How a fat interface spreads change Must-know ​

Coupling channelFat interfaceSegregated interfaces
Compile / static analysisEvery client re-analysed when any method changes (C++ recompilation in 1996; PHPStan/TypeScript today)Only clients of the changed role
Fakes and mocksEvery fake implements every method; mocks need shouldIgnoreMissing() or stubsFakes implement one or two methods
Versioning (libraries)Adding a method to a public interface breaks every implementer outside your repoNew capability goes into a new interface; old implementers unaffected
Deployment (services)One fat API = one deploy queue for every client teamPer-client API or BFF deploys independently
ComprehensionClient code reveals nothing about what it usesParameter type documents the dependency

Adding a method to a published interface Important ​

Adding a method to an interface is a breaking change for every implementer you do not control. Go's standard library therefore never adds methods to io.Reader or fs.FS; it adds new interfaces (fs.ReadFileFS, fs.ReadLinkFS in recent versions) and helper functions that check for them. Java and C# added default interface methods partly to escape this; PHP has neither and relies on new interfaces plus instanceof.

text
1    v1: interface Storage { Get; Put }                     -- 14 third-party implementations
2    v2 (wrong): interface Storage { Get; Put; Watch }      -- 14 implementations fail to compile
3    v2 (right): interface Watcher { Watch }                -- optional; Watch(ctx, s) checks s.(Watcher)
4                                                          -- old implementations keep working, new ones opt in

Measuring it Good to know ​

Simple, useful numbers: for each interface, the number of methods and the number of distinct clients; for each client, the fraction of the interface's methods it calls. An interface where most clients use less than half the methods is a split candidate. In Go, go doc plus grep of call sites is usually enough; in PHP, PhpStorm's "Find usages" per method or a PHPStan custom rule does the same.

Solving the classic problems ​

ProblemSolutionHowAdvantageCost / limitation
God repository used by many controllersRole interfaces per clientOne class implements several roles; container binds eachSmall fakes, focused testsMore names to find
Notifier with email/SMS/pushOne interface per channel capabilitySendsSms, SendsEmail, SendsPushNo LogicException stubsRouter must choose by capability
Vendor SDK with 200 methodsConsumer-defined wrapper roleinterface Payments { charge; refund } + adapterApp depends on 2 methods, not 200Adapter to maintain
Interface grows for one implementationOptional capability interfaceWatcher, LockProvider, ReadFileFSOld implementers unaffectedClients need a fallback
Header interfaces "for mocking"Return structs, define roles at consumersDelete the mirror interfaceLess code, fewer mocksNeeds discipline in reviews
Over-segregated gettersMerge by client useOne role per client use caseReadable signaturesMust re-check clients
One API for mobile, web, partnersBFF or GraphQLPer-client backend or field selectionEach client depends on what it asked forMore deployables or a schema to govern
One fat event for many consumersFine-grained eventsEmailChanged, AddressChangedConsumers subscribe to what they useMore event types to version
Reporting reads the whole schemaPer-client database view + grantCREATE VIEW + GRANT SELECTSchema changes behind the view are invisibleView must be maintained

Segregating database access per client ​

A database is an interface too. A reporting tool, a BI user or another team's service that reads your tables directly depends on every column; a view shaped for that client is a role interface at the data layer, and a grant enforces it.

sql
-- PostgreSQL (MySQL 8, SQL Server, Oracle and SQLite all support views; grants differ by product).
CREATE VIEW reporting.order_facts AS
SELECT o.id, o.placed_at, o.total_cents, o.currency, c.country
FROM   orders o
JOIN   customers c ON c.id = o.customer_id;

CREATE ROLE reporting_reader NOLOGIN;
GRANT USAGE ON SCHEMA reporting TO reporting_reader;
GRANT SELECT ON reporting.order_facts TO reporting_reader;
-- The reporting client can no longer depend on columns it does not use,
-- so renaming orders.internal_notes or splitting customers is invisible to it.
ProductClient-specific "interface" mechanism
PostgreSQLViews, schemas, column-level GRANT, row-level security
MySQL 8 / InnoDBViews, column-level GRANT
SQL ServerViews, schemas, column permissions
OracleViews, synonyms, Virtual Private Database
SQLiteViews (no grants: single-user file)
MongoDBRead-only views (aggregation pipeline), role-based access per collection
RedisACL users restricted to command categories and key patterns (Redis 6+)

Choosing ​

SituationRecommendedExtra techniqueReason
Function needs one behaviour of a big typeNarrowest existing interface (io.Writer, PSR-18)—Most general, easiest to test
Several clients use disjoint method groupsSplit into role interfacesOne class implements all rolesEach client couples to its role
All clients use all methodsKeep one interface—Splitting would over-segregate
Library interface needs a new abilityNew optional interfaceHelper that checks and falls backDo not break implementers
Go package exposing an implementationReturn a structConsumers declare rolesGo wiki guidance
PHP app class with one implementation, no fake neededNo interface at allMake the class finalAn interface with one client and one implementation is overhead
Framework-read flagMarker interface or PHP attribute—One reader, no behaviour
Several frontends with different needsBFF or GraphQLPersisted queriesSystem-level ISP
Many event consumersFine-grained eventsSchema registryConsumers depend on less

In architecture: from a single process to a distributed system ​

Monolith: one process ​

Role interfaces between layers of one codebase. Simplest correct usage: controllers and jobs depend on narrow, client-named interfaces; one service class implements several. Example: a Laravel monolith where LoginController takes FindsUsersByEmail, AdminUserController takes ManagesUsers and the nightly ExportActiveUsers job takes StreamsUsersForReports, all bound to EloquentUsers.

Modular monolith and multiple databases ​

Each module publishes a small facade per consuming module rather than one "module API". Example: Billing exposes InvoiceTotalsForCustomer to Support and InvoicesForExport to Accounting. When billing moves invoices from MySQL to PostgreSQL, neither consumer notices, because neither depended on the table layout; a per-module read view (SQL above) does the same at the database layer.

Microservices: per-client APIs and events ​

The fat interface across a network is the general-purpose API that every client consumes and partly ignores. Sam Newman's Backend for Frontend pattern describes the pressure: "the nature of a mobile experience often differs drastically from a desktop web experience", and a single general-purpose backend "can become a bottleneck when rolling out new delivery". GraphQL solves the same problem by letting each client select exactly the fields it depends on. Events follow the same rule: one UserChanged with every field forces every consumer to parse, version and react to every field.

text
1    mobile ──GET /bff/mobile/home──▶ mobile-bff ──▶ customers (name, avatar) + orders (last 3)
2    web    ──POST /graphql { customer { name orders(last: 20) { total } } }──▶ gateway
3    customers ──EmailChanged──▶ Kafka ──▶ notifications (subscribes)
4    customers ──AddressChanged──▶ Kafka ──▶ shipping (subscribes); analytics subscribes to both
Mobile appWeb appPartner API clientMobile BFFname, avatar, 3 ordersGraphQLclient selects fieldsPartner API v2stable, versioned subsetInternal servicesCustomers (PostgreSQL)Orders (MySQL)Catalog (MongoDB)Sessions (Redis)each client depends only onthe fields it asked forEvents: EmailChanged · AddressChanged · PasswordRotated instead of one fat UserChanged

The diagram shows the system-level version: each client calls an interface shaped for it, and consumers subscribe to fine-grained events instead of one fat UserChanged. Event granularity is covered further in Event-Driven Architecture and Message Design & Schema Evolution.

Distributed data: read models, replicas and caches Good to know ​

CQRS is ISP for data: the write model serves the commands, and each read model is shaped for one query client. Example: orders are written to PostgreSQL; the customer app reads a denormalised order_summary document from MongoDB or a Redis hash; the finance team reads a columnar copy in the warehouse. Each client depends on a model containing exactly its fields, so the write schema can change without breaking them. The cost is synchronisation (outbox or CDC) and staleness. Read replicas are a weaker form: same interface (the whole schema), different instance, so they reduce load but not coupling. See Event Sourcing & CQRS.

Scaling path: 1×, 10×, 100× ​

ScaleWhat ISP looks like
1×: one teamRole interfaces at call sites; no interface without a second implementation or a fake
10×: several teams / modulesPer-consumer module facades; per-client database views; fine-grained events
100×: many clients, public APIsBFF per channel or GraphQL with persisted queries; schema registry; capability interfaces in SDKs instead of growing base interfaces

Lab: refactoring kata ​

Outputs below were produced by running the code on this page with Go 1.27 (module declares go 1.24). PHP steps state the expected observation.

Setup.

bash
cd docs/snippets/solid/go
go vet ./isp/...   # clean

Step 1: measure what each client depends on, before and after.

bash
go run ./isp/kata
# before: Door methods        = 4
# after:  Door methods        = 3
# after:  TimerClient methods = 1

Observation: the security panel's dependency shrank from 4 methods to 3; the timer's from 4 to 1.

Step 2: check whether PlainDoor still lies.

bash
# PlainDoor has TimeOut: before = true after = false

Observation: before the split, PlainDoor satisfied a timer role it cannot play; after, the type system says so.

Step 3: one function, many writers.

bash
# {"title":"isp","body":"small interfaces"}
# buffer bytes = 42

Observation: save.Save wrote to os.Stdout (through io.MultiWriter) and to a bytes.Buffer with no change. Try gzip.NewWriter(os.Stdout) and httptest.NewRecorder() as the writer.

Step 4: an in-memory file system satisfies fs.FS.

bash
# loaded: isp <nil>
# fstest.TestFS: <nil>

Observation: Load works on fstest.MapFS, and fstest.TestFS confirms the fake honours the fs.FS contract (an ISP and an LSP check in one).

Step 5: write a fake for each version. Write a test fake for before.Door and for after.Door. Expected: the first needs four methods, one of which (TimeOut) the test never calls; the second needs three.

Step 6 (Laravel): split the notifier. In a Laravel 13 app, bind SendsSms to an SMS channel and inject it into OtpService. Expected before (with NotificationChannel): a test fake must implement sendEmail and sendPush; calling either on SmsChannel throws LogicException. Expected after: the fake is one method, and php artisan test no longer touches email or push code paths. Then add implements MustVerifyEmail to User and observe that only the verification flow changes (the verified middleware starts redirecting unverified users).

Common misconceptions ​

BeliefReality
"Every interface should have one method."Cohesion per client is the test; sort.Interface (3) and PSR-3 (9) are fine.
"ISP is about recompilation in C++."The coupling it describes shows up in fakes, versioning, deployment and comprehension in every language.
"ISP means splitting classes."It splits interfaces; one class can implement several roles.
"Extract Interface on the whole class is good practice."That produces a header interface; derive roles from call sites.
"The implementer should export an interface for mocking."Go wiki: define interfaces where they are used; return concrete types.
"A type assertion to another interface is always a smell."Optional capability checks with a fallback (fs.ReadFileFS) are a designed pattern.
"Marker interfaces are useless."Laravel's ShouldQueue is a precise opt-in read by one component.
"More interfaces are always more flexible."Over-segregation scatters one role across many names.
"Adding a method to an interface is a small change."It breaks every implementer you do not control.
"BFF is just an API gateway."A BFF is owned by and shaped for one client; a gateway is shared infrastructure.
"GraphQL removes the need to design for clients."It moves the segregation into queries; you still govern the schema and persisted queries.
"One event with every field is simpler for consumers."Every consumer then depends on every field and every change.

Cheat sheet ​

TopicWhat to remember
RuleClients should not be forced to depend on methods they do not use
SloganSeparate Clients mean Separate Interfaces (Martin 1996)
Role vs headerRole: shaped by one collaboration. Header: mirrors a class
Go idiomAccept interfaces, return structs; define interfaces in the consumer
ProverbThe bigger the interface, the weaker the abstraction
CompositionEmbed small interfaces (io.ReadWriteCloser) instead of writing a big one
Optional capabilitiesBase interface complete; extras as separate interfaces with a fallback
Marker interfacesLaravel ShouldQueue, ShouldBeUnique; one reader, no methods
Laravel authAuthenticatable, CanResetPassword, MustVerifyEmail, Authorizable
PSRsPSR-11 two methods; PSR-18 one; PSR-7 split per message type
Stop splitting whenEvery client uses every method of the interface
Library evolutionNew ability = new interface, never a new method on a published one
System levelBFF, GraphQL selection, fine-grained events, CQRS read models, DB views
SmellStub methods, LogicException for unsupported calls, 25-method mocks

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — In Martin's example, why is adding TimeOut to Door harmful even for doors that never time out? Must-know ​

Answer

Answer: Every Door implementation must now carry a TimeOut it cannot honour, and every client of Door is coupled to changes in the timer protocol, although only TimedDoor needs it.

2 — What is the difference between a role interface and a header interface? Important ​

Answer

Answer: A role interface is defined by one collaboration's needs (Fowler); a header interface mirrors the public methods of a class. Role interfaces follow ISP; header interfaces do not.

3 — Why does the Go wiki say to define interfaces in the consuming package? Must-know ​

Answer

Answer: The consumer knows which methods it uses, implicit satisfaction means the implementer need not change, and returning concrete types lets implementations grow without refactoring callers.

4 — sort.Interface has three methods. Is it fat? Must-know ​

Answer

Answer: No. Its one client, sort.Sort, needs all three methods; splitting would over-segregate.

5 — When is a type assertion to an interface acceptable rather than a smell? Important ​

Answer

Answer: When it checks an optional capability (fs.ReadFileFS, io.WriterTo, LockProvider) whose absence is part of the documented base contract and the caller has a correct fallback or a documented error.

6 — Which Laravel contracts split the user model's responsibilities by client? Good to know ​

Answer

Answer: Authenticatable (guards), CanResetPassword (password broker), MustVerifyEmail (verification, opt-in) and Authorizable (gate).

7 — What is a marker interface, and give a Laravel example. Good to know ​

Answer

Answer: An interface with no methods used as a flag read via instanceof; ShouldQueue tells Laravel to queue a job, listener, mailable or notification.

8 — You must add Watch to a published Storage interface. What do you do? Important ​

Answer

Answer: Add a separate optional Watcher interface and a helper that checks for it, instead of adding a method that breaks every existing implementer.

9 — How is a Backend for Frontend an application of ISP? Important ​

Answer

Answer: Each client type gets an API shaped to its needs instead of depending on one general-purpose API with fields and endpoints it does not use.

10 — Why are fine-grained events (EmailChanged) often better than one UserChanged? Important ​

Answer

Answer: Consumers subscribe to and parse only what they use, so changes to unrelated fields do not force them to change or redeploy.

11 — What does over-segregation look like and how do you fix it? Important ​

Answer

Answer: Interfaces per getter or per CRUD verb that every client always uses together; merge them into one role per client use case.

Glossary ​

TermMeaning
Interface Segregation Principle (ISP)Clients should not be forced to depend upon interfaces they do not use
Interface pollutionAdding a method to a shared interface for one implementation's benefit
Fat interfaceA non-cohesive interface serving several kinds of clients
Role interfaceInterface defined by one interaction between supplier and consumer (Fowler)
Header interfaceInterface that mirrors a class's whole public API (Fowler)
Client-specific interfaceInterface containing exactly the methods one client uses
Consumer-defined interfaceGo practice of declaring the interface in the package that uses it
Accept interfaces, return structsGo idiom: parameters are small interfaces, results are concrete types
Small interfaceInterface with one or a few methods; the Go norm
Composition (interface embedding)Building a larger interface from smaller ones
Optional interface / capability interfaceExtra interface an implementation may add; clients check and fall back
Type assertionGo v.(I) check used for optional capabilities
Marker interfaceInterface with no methods read as a flag (ShouldQueue)
Over-segregationSplitting a cohesive role into fragments no client uses alone
Cohesion (client-side)Degree to which an interface's methods are used together by its clients
io.Reader / io.Writer / io.ReadWriteCloserGo's one-method I/O interfaces and their composition
fs.FS / ReadFileFSGo's minimal file-system interface and an optional capability
fstestGo package that tests fs.FS implementations
StringerGo's fmt.Stringer, one method String()
http.HandlerGo's one-method HTTP abstraction ServeHTTP
Authenticatable / CanResetPassword / MustVerifyEmailLaravel auth contracts, each for a different framework client
ShouldQueue / ShouldBeUniqueLaravel queue marker interfaces
Store / Repository / LockProviderLaravel cache contracts for drivers, application code, and lock-capable stores
PSR-3, PSR-7, PSR-11, PSR-18PHP-FIG standards for logging, HTTP messages, containers and HTTP clients
Backend for Frontend (BFF)A backend per client type, shaped and often owned by that client's team
GraphQLQuery language where the client selects exactly the fields it depends on
Event granularityHow much one event carries; fine-grained events reduce consumer coupling
Read model / CQRSA data model shaped for one query client, separate from the write model
Separate Clients mean Separate InterfacesMartin's 1996 slogan for ISP
Pike / Cheney / FowlerGo Proverbs author; SOLID Go Design author; author of RoleInterface/HeaderInterface

References ​

Built by Morteza Negahi