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 for | Go to |
|---|---|
| The principle in tables | Everything in one minute |
| Why it exists, the trade-off | Why ISP exists |
| Martin's door and timer, Fowler, Pike, Cheney | Where it comes from |
| Fat interface, role vs header, client-specific, composition, optional and marker interfaces, over-segregation | The concepts, one by one |
| How each language and framework expresses it | Per-language behaviour |
| Go and Laravel before/after code | Go, Laravel |
| Change propagation, recompilation, mocks, method counts | Mechanics |
| Splitting a repository, a notifier, an SDK wrapper, a God service | Solving the classic problems |
| When to split and when to stop | Choosing |
| BFF, GraphQL, events, read models, database views | In architecture |
| Refactoring kata with real output | Lab |
| Wrong beliefs, cheat sheet, terms | Misconceptions, Cheat sheet, Glossary |
Everything in one minute
The vocabulary.
| Term | In plain words | Tiny example | Good or bad |
|---|---|---|---|
| Fat interface | One interface serving several kinds of clients | Door with Lock, Unlock, IsOpen, TimeOut | Bad when clients differ |
| Interface pollution | A method added to a shared interface for one implementation's benefit | TimeOut added to Door for TimedDoor | Bad |
| Header interface | An interface that copies a class's whole public API | UserServiceInterface with all 25 methods | Usually bad |
| Role interface | An interface shaped by one collaboration | TimerClient { TimeOut() } | Good |
| Client-specific interface | Defined from the client's point of view | OtpService needs SendsSms | Good |
| Consumer-defined interface (Go) | Declared in the package that uses it | type orderMarker interface{ MarkPaid(...) } in checkout | Good |
| Optional capability interface | Extra interface an implementation may add | fs.ReadFileFS, Laravel LockProvider | Good if the base is complete |
| Marker interface | Interface with no methods, read as a flag | Laravel ShouldQueue | Fine, use sparingly |
| Over-segregation | So many tiny interfaces that nothing is cohesive | HasId, HasName, HasEmail for one entity | Bad |
The test.
| Question | If 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.
| Situation | Do this |
|---|---|
| Writing a function or class | Accept the smallest interface that names what you use |
| Writing an implementation | Return the concrete type; let consumers define the interfaces they need |
| Designing an API or event | Shape 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 interface | Several role interfaces |
|---|---|
| One name to learn, easy to discover | Several names, each meaningful to its client |
| Every client couples to every method | Each client couples to what it uses |
| Fakes must implement everything | Fakes implement one or two methods |
| Implementations stub what they cannot do | Implementations implement only what they do |
| A change ripples to all clients | A change touches only the role's clients |
| Fine when all clients use everything | Overkill 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
- "Every interface should have one method." The test is per-client cohesion, not a count.
sort.Interfacehas three methods and is perfectly segregated because its only client,sort.Sort, needs all three. - "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.
- "Split the implementation into many classes." ISP splits interfaces. One class may implement several role interfaces (Martin's
TimedDoorimplementsDoorandTimerClient); 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".
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".
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 DoorReal 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.
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 changesReal 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.
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 implicitlyReal 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).
| Language | Where client-specific interfaces naturally live | Implementer must declare it? |
|---|---|---|
| Go | Consumer package, often unexported | No (implicit satisfaction) |
| PHP / Laravel | App\Contracts or the consuming module | Yes (implements) |
| Java | Consumer module (or a separate API module) | Yes |
| C# | Consumer assembly | Yes |
| TypeScript | Anywhere; Pick<T, 'a' | 'b'> derives one from a class type | No (structural) |
| Python | typing.Protocol in the consumer module | No (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.
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 canReal 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.
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 interface | Base interface | Fallback when absent |
|---|---|---|
Go fs.ReadFileFS, fs.StatFS, fs.ReadDirFS | fs.FS | Open and read/stat through the file |
Go io.WriterTo, io.ReaderFrom | io.Reader, io.Writer | io.Copy uses a buffer |
Go http.Flusher | http.ResponseWriter | No streaming; response is buffered |
Laravel Illuminate\Contracts\Cache\LockProvider | Illuminate\Contracts\Cache\Store | BadMethodCallException (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."
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 componentReal 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.
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 methodsReal 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
| Capability | Go | PHP / Laravel | Java | C# | TypeScript | Python |
|---|---|---|---|---|---|---|
| Interfaces satisfied | Implicitly (structural) | Explicitly (implements) | Explicitly | Explicitly | Structurally | Nominal (ABC) or structural (Protocol) |
| Define role after the fact (no change to implementer) | Yes | No (adapter needed) | No (adapter) | No (adapter) | Yes | Yes with Protocol |
| Compose interfaces | Embedding | interface A extends B, C | extends B, C | : IB, IC | A & B, extends | Multiple Protocol bases |
| Derive a narrow view of a class | Declare a small interface | Declare a small interface | Same | Same | Pick<Class, 'm1' | 'm2'> | Protocol with the used methods |
| Default methods on interfaces | No | No (traits instead) | Yes (Java 8+) | Yes (C# 8+) | No | Yes (ABC/Protocol bodies) |
| Optional capability check | Type assertion v.(I) | instanceof | instanceof | is / as | Type guard | isinstance with runtime_checkable |
| Marker interfaces common | No (prefer unexported methods) | Yes (ShouldQueue) | Yes (Serializable) | Rare (attributes) | No | Rare |
| Framework / standard | Segregated contracts it ships |
|---|---|
| Go stdlib | io.Reader, io.Writer, io.Closer, io.Seeker, composed io.ReadWriteCloser; fmt.Stringer; http.Handler (one method); fs.FS + ReadFileFS/StatFS/ReadDirFS/GlobFS/SubFS |
| Laravel 13 | Authenticatable, CanResetPassword, MustVerifyEmail, Authorizable; cache Store vs Repository vs LockProvider; ShouldQueue, ShouldBeUnique, ShouldBeEncrypted |
| PHP-FIG PSRs | PSR-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) |
| Java | Iterable → Collection → List; AutoCloseable; Comparable |
| .NET | IEnumerable<T>, IReadOnlyCollection<T>, IReadOnlyList<T> alongside IList<T>; IDisposable |
| NestJS / Spring | Lifecycle 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.
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.
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.
// 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.
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
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
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
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 channel | Fat interface | Segregated interfaces |
|---|---|---|
| Compile / static analysis | Every client re-analysed when any method changes (C++ recompilation in 1996; PHPStan/TypeScript today) | Only clients of the changed role |
| Fakes and mocks | Every fake implements every method; mocks need shouldIgnoreMissing() or stubs | Fakes implement one or two methods |
| Versioning (libraries) | Adding a method to a public interface breaks every implementer outside your repo | New capability goes into a new interface; old implementers unaffected |
| Deployment (services) | One fat API = one deploy queue for every client team | Per-client API or BFF deploys independently |
| Comprehension | Client code reveals nothing about what it uses | Parameter 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.
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 inMeasuring 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
| Problem | Solution | How | Advantage | Cost / limitation |
|---|---|---|---|---|
| God repository used by many controllers | Role interfaces per client | One class implements several roles; container binds each | Small fakes, focused tests | More names to find |
| Notifier with email/SMS/push | One interface per channel capability | SendsSms, SendsEmail, SendsPush | No LogicException stubs | Router must choose by capability |
| Vendor SDK with 200 methods | Consumer-defined wrapper role | interface Payments { charge; refund } + adapter | App depends on 2 methods, not 200 | Adapter to maintain |
| Interface grows for one implementation | Optional capability interface | Watcher, LockProvider, ReadFileFS | Old implementers unaffected | Clients need a fallback |
| Header interfaces "for mocking" | Return structs, define roles at consumers | Delete the mirror interface | Less code, fewer mocks | Needs discipline in reviews |
| Over-segregated getters | Merge by client use | One role per client use case | Readable signatures | Must re-check clients |
| One API for mobile, web, partners | BFF or GraphQL | Per-client backend or field selection | Each client depends on what it asked for | More deployables or a schema to govern |
| One fat event for many consumers | Fine-grained events | EmailChanged, AddressChanged | Consumers subscribe to what they use | More event types to version |
| Reporting reads the whole schema | Per-client database view + grant | CREATE VIEW + GRANT SELECT | Schema changes behind the view are invisible | View 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.
-- 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.| Product | Client-specific "interface" mechanism |
|---|---|
| PostgreSQL | Views, schemas, column-level GRANT, row-level security |
| MySQL 8 / InnoDB | Views, column-level GRANT |
| SQL Server | Views, schemas, column permissions |
| Oracle | Views, synonyms, Virtual Private Database |
| SQLite | Views (no grants: single-user file) |
| MongoDB | Read-only views (aggregation pipeline), role-based access per collection |
| Redis | ACL users restricted to command categories and key patterns (Redis 6+) |
Choosing
| Situation | Recommended | Extra technique | Reason |
|---|---|---|---|
| Function needs one behaviour of a big type | Narrowest existing interface (io.Writer, PSR-18) | — | Most general, easiest to test |
| Several clients use disjoint method groups | Split into role interfaces | One class implements all roles | Each client couples to its role |
| All clients use all methods | Keep one interface | — | Splitting would over-segregate |
| Library interface needs a new ability | New optional interface | Helper that checks and falls back | Do not break implementers |
| Go package exposing an implementation | Return a struct | Consumers declare roles | Go wiki guidance |
| PHP app class with one implementation, no fake needed | No interface at all | Make the class final | An interface with one client and one implementation is overhead |
| Framework-read flag | Marker interface or PHP attribute | — | One reader, no behaviour |
| Several frontends with different needs | BFF or GraphQL | Persisted queries | System-level ISP |
| Many event consumers | Fine-grained events | Schema registry | Consumers 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.
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 bothThe 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×
| Scale | What ISP looks like |
|---|---|
| 1×: one team | Role interfaces at call sites; no interface without a second implementation or a fake |
| 10×: several teams / modules | Per-consumer module facades; per-client database views; fine-grained events |
| 100×: many clients, public APIs | BFF 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.
cd docs/snippets/solid/go
go vet ./isp/... # cleanStep 1: measure what each client depends on, before and after.
go run ./isp/kata
# before: Door methods = 4
# after: Door methods = 3
# after: TimerClient methods = 1Observation: 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.
# PlainDoor has TimeOut: before = true after = falseObservation: before the split, PlainDoor satisfied a timer role it cannot play; after, the type system says so.
Step 3: one function, many writers.
# {"title":"isp","body":"small interfaces"}
# buffer bytes = 42Observation: 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.
# 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
| Belief | Reality |
|---|---|
| "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
| Topic | What to remember |
|---|---|
| Rule | Clients should not be forced to depend on methods they do not use |
| Slogan | Separate Clients mean Separate Interfaces (Martin 1996) |
| Role vs header | Role: shaped by one collaboration. Header: mirrors a class |
| Go idiom | Accept interfaces, return structs; define interfaces in the consumer |
| Proverb | The bigger the interface, the weaker the abstraction |
| Composition | Embed small interfaces (io.ReadWriteCloser) instead of writing a big one |
| Optional capabilities | Base interface complete; extras as separate interfaces with a fallback |
| Marker interfaces | Laravel ShouldQueue, ShouldBeUnique; one reader, no methods |
| Laravel auth | Authenticatable, CanResetPassword, MustVerifyEmail, Authorizable |
| PSRs | PSR-11 two methods; PSR-18 one; PSR-7 split per message type |
| Stop splitting when | Every client uses every method of the interface |
| Library evolution | New ability = new interface, never a new method on a published one |
| System level | BFF, GraphQL selection, fine-grained events, CQRS read models, DB views |
| Smell | Stub methods, LogicException for unsupported calls, 25-method mocks |
Self-check: questions & answers
- 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
| Term | Meaning |
|---|---|
| Interface Segregation Principle (ISP) | Clients should not be forced to depend upon interfaces they do not use |
| Interface pollution | Adding a method to a shared interface for one implementation's benefit |
| Fat interface | A non-cohesive interface serving several kinds of clients |
| Role interface | Interface defined by one interaction between supplier and consumer (Fowler) |
| Header interface | Interface that mirrors a class's whole public API (Fowler) |
| Client-specific interface | Interface containing exactly the methods one client uses |
| Consumer-defined interface | Go practice of declaring the interface in the package that uses it |
| Accept interfaces, return structs | Go idiom: parameters are small interfaces, results are concrete types |
| Small interface | Interface with one or a few methods; the Go norm |
| Composition (interface embedding) | Building a larger interface from smaller ones |
| Optional interface / capability interface | Extra interface an implementation may add; clients check and fall back |
| Type assertion | Go v.(I) check used for optional capabilities |
| Marker interface | Interface with no methods read as a flag (ShouldQueue) |
| Over-segregation | Splitting 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.ReadWriteCloser | Go's one-method I/O interfaces and their composition |
fs.FS / ReadFileFS | Go's minimal file-system interface and an optional capability |
fstest | Go package that tests fs.FS implementations |
Stringer | Go's fmt.Stringer, one method String() |
http.Handler | Go's one-method HTTP abstraction ServeHTTP |
Authenticatable / CanResetPassword / MustVerifyEmail | Laravel auth contracts, each for a different framework client |
ShouldQueue / ShouldBeUnique | Laravel queue marker interfaces |
Store / Repository / LockProvider | Laravel cache contracts for drivers, application code, and lock-capable stores |
| PSR-3, PSR-7, PSR-11, PSR-18 | PHP-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 |
| GraphQL | Query language where the client selects exactly the fields it depends on |
| Event granularity | How much one event carries; fine-grained events reduce consumer coupling |
| Read model / CQRS | A data model shaped for one query client, separate from the write model |
| Separate Clients mean Separate Interfaces | Martin's 1996 slogan for ISP |
| Pike / Cheney / Fowler | Go Proverbs author; SOLID Go Design author; author of RoleInterface/HeaderInterface |
References
- Robert C. Martin, "The Interface Segregation Principle", Engineering Notebook, The C++ Report, 1996. PDF
- Martin Fowler, "RoleInterface" and "HeaderInterface", bliki, 2006. RoleInterface, HeaderInterface
- Rob Pike, Go Proverbs, Gopherfest SV 2015. go-proverbs.github.io
- Go Wiki, "Go Code Review Comments: Interfaces". go.dev
- Dave Cheney, "SOLID Go Design", 2016. dave.cheney.net
- Go documentation:
io,io/fs; source fs.go - Laravel 13 documentation: Contracts, Authentication, Email Verification, Queues, Cache; framework source Foundation/Auth/User.php
- PHP-FIG, PSR-11 Container Interface. php-fig.org
- Sam Newman, "Pattern: Backends For Frontends", 2015. samnewman.io
- GraphQL, "Queries". graphql.org
- NestJS documentation, "Providers". docs.nestjs.com