SOLID: five principles for code that survives change
"I think it was 2004 and Michael wrote me an e-mail, and said that if you rearranged the principles they spell SOLID." — Robert C. Martin, interviewed by Wesley Reisz, Uncle Bob Martin on Clean Software, Craftsperson, Origins of SOLID, DDD, & Software Ethics, InfoQ podcast, 2018
Summary: SOLID is five design principles that together answer one question: when requirements change, how much of my code has to change with them? All five are about the direction and size of dependencies. Focus: Where each principle came from (1972 to 2014), how the five form one argument about dependency direction, how they look in Go, Laravel, Java, .NET, TypeScript and Python, what the critics say, and how to measure a codebase against them. Learning goal: Explain SOLID as one argument rather than five slogans, recognise which principle a design problem calls for, and know where on the Design path to go next.
This page is the entry to the Design path of the site and the overview of the SOLID chapter. It gives the history, the shared vocabulary and the comparison across languages, and then hands each principle to its own chapter: Single Responsibility, Open–Closed, Liskov Substitution, Interface Segregation and Dependency Inversion. Each chapter quotes the original papers, shows the principle broken and honoured in Go and Laravel, and follows it from one class to a distributed system.
Page map
| If you are looking for | Go to |
|---|---|
| The five principles on one screen | Everything in one minute |
| What problem SOLID solves | Why SOLID exists |
| 1972 → 2004 → today, with primary sources | Where it comes from |
| Each principle in plain words, with its usual misreading | The principles, one by one |
| How the five fit together | One argument: dependency direction |
| Go vs PHP vs Java vs C# vs TypeScript vs Python | SOLID across languages |
| Measuring dependencies: instability, abstractness, change coupling | Mechanics |
| CUPID, performance, "a little copying" | Critiques |
| Which principle for which symptom | Solving the classic problems, Choosing |
| SOLID from a monolith to microservices | In architecture |
| The Design path and reading order | The Design path |
| A lab that measures your own codebase | Lab |
| Wrong beliefs, cheat sheet, self-check, all SOLID terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The five principles.
| Letter | Principle | The one-line rule (original wording where it exists) | Plain words | Original source |
|---|---|---|---|---|
| S | Single Responsibility | "THERE SHOULD NEVER BE MORE THAN ONE REASON FOR A CLASS TO CHANGE." | One module answers to one group of people | Martin, Agile Software Development (2002); "about people" in his 2014 post |
| O | Open–Closed | "Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification." | Add features by adding code, not by editing working code | Meyer (1988); Martin, C++ Report (1996) |
| L | Liskov Substitution | Subtypes must be usable through the base type without the caller noticing | A plug-in must keep the promises of the socket | Liskov, OOPSLA keynote (1987); Liskov & Wing (1994); Martin (March 1996) |
| I | Interface Segregation | Clients should not be forced to depend on interfaces they do not use | Small, role-shaped interfaces | Martin, C++ Report (1996) |
| D | Dependency Inversion | "High level modules should not depend upon low level modules. Both should depend upon abstractions." | Business rules own the interfaces; databases and frameworks plug in | Martin, C++ Report (May 1996) |
What design rot looks like (Martin's 2000 paper names four symptoms; SOLID is the treatment).
| Symptom | Martin's description, shortened | Typical cause | Principle that helps most |
|---|---|---|---|
| Rigidity | Every change causes a cascade of changes in dependent modules | Dependencies on concrete details | DIP, OCP |
| Fragility | Software breaks in places with no conceptual relationship to the change | Several actors in one module | SRP, LSP |
| Immobility | Useful parts cannot be reused without dragging everything along | Policy tangled with details | DIP, ISP |
| Viscosity | Doing the right thing is harder than the hack | Abstractions that fight the change | OCP, SRP |
The one-sentence version.
| If you remember one thing | It is this |
|---|---|
| What SOLID is about | Controlling the direction and size of dependencies |
| What it is not | Rules of syntax, class counts, or a requirement to use inheritance |
| How to apply it | Ask "who will change this, and what will that change touch?" |
Why SOLID exists
Martin's 2000 paper Design Principles and Design Patterns opens with software that starts clean and then "starts to rot": every change takes longer, fixes break unrelated features, nothing can be reused, and the hack becomes easier than the right change. His diagnosis is that rot is caused by dependencies that are uncontrolled: modules depend on details they should not know about, so changes to those details propagate. Each SOLID principle is a rule for one kind of dependency.
| Code without the principles | Code with the principles |
|---|---|
| Fewer types, fewer files at the start | More types and files, each with a clear owner |
| Policy calls the database, the HTTP client and the mailer directly | Policy calls small interfaces it owns; details plug in |
| A new requirement edits working code | A new requirement mostly adds code |
| Tests need the whole stack | Rules are tested in memory |
| Fast to write the first version | Faster to change the twentieth version |
| Risk: rot | Risk: over-engineering, speculative abstractions |
The analogy we reuse on this page: a building's electrical system. SRP: each circuit serves one area, so the kitchen electrician never cuts power to the server room. OCP: sockets let you add appliances without rewiring. LSP: any appliance with a compliant plug must behave like an appliance on that circuit; one that draws ten times the rated current "fits" but breaks the promise. ISP: there are different socket types for different needs instead of one socket with forty pins. DIP: appliances are built to the socket standard, not to your house; the standard is owned by neither.
Three common misunderstandings, up front
- "SOLID is object-oriented, so it does not apply to Go or to Laravel apps." The principles are about dependencies, and every language has those. Dave Cheney's SOLID Go Design (2016) maps each principle to packages, interfaces and the import graph.
- "SOLID means many small classes and interfaces everywhere." Each principle has a cost. Martin's own 1996 OCP column says closure "must be strategic". Abstractions earn their place when a real second actor or variant exists.
- "The five are independent rules." They are one argument (see below): DIP sets the direction, OCP explains why, LSP makes extension safe, ISP keeps the abstractions small, SRP draws the borders.
Where it comes from
The timeline above reads left to right: the roots in structured design, Meyer's and Liskov's work, Martin's columns, paper and book, the acronym, his later posts, and the critiques.
| Year | Event | What it added | Source we read |
|---|---|---|---|
| 1968 | Conway, How Do Committees Invent? | Systems copy the communication structure of their organisation | melconway.com |
| 1972 | Parnas, On the Criteria To Be Used in Decomposing Systems into Modules | Information hiding: each module hides a decision likely to change | CACM paper (PDF) |
| 1974 | Stevens, Myers, Constantine, Structured Design | Coupling and cohesion ("binding") as measures | IBM Systems Journal reprint |
| 1987 | Liskov, Data Abstraction and Hierarchy (OOPSLA keynote) | The substitution property | See LSP |
| 1988 | Meyer, Object-Oriented Software Construction | "open and closed" modules | Via Martin 1996 and 2014 |
| 1996 | Martin's Engineering Notebook columns in The C++ Report | OCP (his first column), LSP (March), DIP (May), ISP (the column after DIP) | Duke course PDFs |
| 2000 | Martin, Design Principles and Design Patterns | Four class principles (OCP, LSP, DIP, ISP), six package principles, the rot symptoms; no SRP yet | |
| 2002 | Martin, Agile Software Development: Principles, Patterns, and Practices | SRP chapter: "never more than one reason for a class to change" | Object Mentor chapter draft |
| 2004 | Michael Feathers rearranges the initials | The word SOLID | InfoQ 2018 |
| 2012 | Martin, The Clean Architecture | The Dependency Rule for whole systems | cleancoder blog |
| 2014 | Martin's SRP and OCP posts | SRP "is about people"; OCP's apotheosis is the plugin | cleancoder blog |
| 2016 | Cheney, SOLID Go Design | SOLID without classes | dave.cheney.net |
| 2021–2022 | Dan North, CUPID | A critique and an alternative set of properties | dannorth.net |
| 2023 | Muratori, "Clean" Code, Horrible Performance | The runtime cost of polymorphism-first rules | computerenhance.com |
The name. Martin recalls that Michael Feathers suggested the ordering in an email; he adds that "it turned out to be a good brand and worked out pretty well." So S‑O‑L‑I‑D has no deep meaning; it is the arrangement that spelled a word.
Whose principles. Martin does not claim all five. OCP is Meyer's and LSP is Liskov's. In the InfoQ interview he attributes both OCP and SRP to Meyer (the transcript spells the name "Bertram Mayer"), and his 2014 SRP post says "I have this vague feeling that I stole the name of this principle from Bertrand Meyer, but I have not been able to confirm that." His contribution was to articulate ISP, DIP and SRP and to connect all five.
A correction to a common story. SOLID is often said to have been introduced in the 2000 paper. The paper does contain four of the five and introduces the package principles, but SRP is not in it; its closest relative there is the Common Closure Principle, "Classes that change together, belong together." SRP as a named class principle appears in the 2002 book.
From classes to systems, 2012. The Clean Architecture post applies DIP to a whole application:
"The overriding rule that makes this architecture work is The Dependency Rule. This rule says that source code dependencies can only point inwards." — Robert C. Martin, The Clean Architecture, The Clean Code Blog, 13 August 2012
The principles, one by one
Each block is a summary; the chapter linked in the heading has the full treatment.
S: Single Responsibility Must-know
In plain words: put the code that one group of people asks you to change in one place, and keep it apart from code that other groups change.
Common misunderstanding: "a class should do one thing." That is a function-level readability rule; SRP is about reasons to change, and Martin's 2014 post says the reasons are people.
Definition: a module should have one, and only one, reason to change; equivalently, "Gather together the things that change for the same reasons. Separate those things that change for different reasons."
Week Request One Employee type Split by actor
1 W1 finance: overtime after 7h edit Employee (shared) edit payroll
2 W1 -- audit report changes too, nobody asked -- report unchangedReal scenario: a Laravel User model edited by auth, billing and marketing teams; a Go server package holding routing, SQL and pricing.
O: Open–Closed Must-know
In plain words: for the changes you expect, add new code instead of editing code that works.
Common misunderstanding: "never edit existing code" or "put an interface on everything." Closure is strategic: choose the axis of change, and abstract when the variants are real.
Definition: a module that depends on a fixed abstraction is closed for modification; it is extended by adding new implementations of that abstraction.
Request Growing switch Registry / interface
1 add push channel edit constant, Validate, Send new package + 1 import line
2 retest email, sms yes (same function edited) noReal scenario: Go's database/sql drivers; Laravel's Cache::extend, Storage::extend, Auth::extend.
L: Liskov Substitution Must-know
In plain words: anything that claims to implement an interface must keep all of its promises, so the caller never has to check which implementation it got.
Common misunderstanding: "if it compiles, it substitutes." Types check the method signatures; LSP is about behaviour: preconditions, postconditions, invariants, errors and side effects.
Definition: Martin's 1996 C++ wording, quoted in his DIP column: "every function which operates upon a reference or pointer to a base class, should be able to operate upon derivatives of that base class without knowing it."
Caller FileStore ReadOnlyStore (violates LSP)
1 store.Save(doc) ok panics "read only"
2 caller adds `if store is ReadOnlyStore` checks -> OCP lost as wellReal scenario: a cache implementation that silently drops writes over 1 MB; an io.Reader that returns 0, nil forever; "Repeatable Read" meaning different guarantees in PostgreSQL and MySQL InnoDB (the database-level analogue, see Isolation Levels).
I: Interface Segregation Must-know
In plain words: give each client an interface with only the methods it uses.
Common misunderstanding: "one method per interface, always." The rule is client-shaped, not tiny: an interface is as big as the role its client needs.
Definition: clients should not be forced to depend on methods they do not use; split fat interfaces into role interfaces. Rob Pike's Go proverb says it in six words: "The bigger the interface, the weaker the abstraction."
Change Fat Repository interface Role interfaces
1 add BulkExport() for analytics every fake and every client only the Exporter role
recompiles / updatesReal scenario: Go's io.Reader, io.Writer and io.ReadWriter; Laravel's narrow contracts such as Illuminate\Contracts\Cache\Repository vs the whole cache manager.
D: Dependency Inversion Must-know
In plain words: your business rules define the interfaces they need; the database, the HTTP client and the framework implement them.
Common misunderstanding: "DIP means using a dependency injection container." Injection is one technique; DIP is about who owns the abstraction and which way the source-code arrow points.
Definition: "High level modules should not depend upon low level modules. Both should depend upon abstractions. Abstractions should not depend upon details. Details should depend upon abstractions." (Martin, May 1996)
Before: OrderService --imports--> postgres.Repo (policy depends on detail)
After: OrderService --owns--> OrderStore <--implements-- postgres.Repo
main wires postgres.Repo into OrderService (detail depends on policy)Real scenario: swapping PostgreSQL for MySQL, SQLite in tests, or a MongoDB-backed store without touching the use case; the Clean Architecture's inward-pointing rings.
Coupling, cohesion and the package principles Good to know
In plain words: SOLID has a second half for packages (Go packages, Composer packages, Java modules) that few people learn: what to put together, and which way packages may depend on each other.
Common misunderstanding: "SOLID is only about classes." Martin's 2000 paper gives as much space to package principles.
Definition:
| Principle | Wording in the 2000 paper | Concern |
|---|---|---|
| REP, Release Reuse Equivalency | "The granule of reuse is the granule of release." | Cohesion: release what is reused together |
| CCP, Common Closure | "Classes that change together, belong together." | Cohesion: SRP for packages |
| CRP, Common Reuse | Classes that are not reused together should not be grouped together | Cohesion: ISP for packages |
| ADP, Acyclic Dependencies | No cycles in the package dependency graph | Coupling (Go's compiler enforces it) |
| SDP, Stable Dependencies | "Depend in the direction of stability." | Coupling |
| SAP, Stable Abstractions | Stable packages should be abstract | Coupling: DIP for packages |
Fix: measure them with the instability and abstractness metrics.
One argument: dependency direction
Read the picture from the centre outwards. The business policy sits in the middle and owns small interfaces. Everything concrete (HTTP handlers, queue workers, the PostgreSQL repository, the Stripe gateway) points inward at those interfaces.
- DIP sets the direction: the important parts of the program, the business policy, do not depend on the incidental parts. Both depend on abstractions, and the abstractions belong to the policy.
- OCP explains why that pays: a policy that depends on a fixed abstraction can gain behaviour by adding implementations, without being edited.
- LSP is the fine print that makes OCP safe: a new implementation may be dropped in only if it keeps the abstraction's promises. Otherwise every "extension" quietly modifies the callers' assumptions.
- ISP keeps the abstractions small enough that each client depends only on what it uses, so a change for one client does not ripple to another.
- SRP draws the borders: each module answers to one actor, so a request from one actor lands in one place.
Change request Principle that keeps it local
1 "support a new payment gateway" OCP (new implementation), LSP (it must behave)
2 "move from MySQL to PostgreSQL" DIP (store interface owned by policy)
3 "analytics needs a bulk export" ISP (new role interface, others untouched)
4 "finance changes the VAT rule" SRP (pricing module only)SOLID across languages
| Principle | Go | PHP / Laravel | Java / Spring | C# / .NET | TypeScript | Python |
|---|---|---|---|---|---|---|
| SRP unit | Package (Cheney: "a single unit of change") | Class + framework slot (Form Request, Action, Policy, Job) | Class + package / module | Class + assembly | ES module | Module / package |
| OCP mechanism | Small interfaces, Register + init(), embedding, generics | Contracts + container, Manager::extend, events | Interfaces, autowired collections, ServiceLoader | Interfaces, DI with multiple or keyed registrations | Structural interfaces, plugin arrays | Protocols/ABCs, entry points, singledispatch |
| LSP check | Behavioural contract tests; no inheritance to abuse | Contract tests; return-type covariance rules in PHP | Contract tests; inheritance makes violations easy | Same as Java | Structural typing checks shape, not behaviour | Duck typing checks nothing at definition time |
| ISP shape | One-method interfaces (io.Reader); defined by the consumer | Narrow contracts; role interfaces | Role interfaces; default methods blur it | Role interfaces | Pick<T, K>, small interfaces | typing.Protocol per role |
| DIP wiring | Manual in main (composition root) | Service container, service providers | Spring IoC container | Microsoft.Extensions.DependencyInjection | Manual or a DI library | Manual or a DI library |
| Typical violation | package utils; 20-method interfaces copied from Java | Fat controller, god model, new inside services | Anaemic services with everything injected | Same as Java | Barrel files that import everything | God modules, circular imports |
Two language features change the picture. Implicit interfaces (Go, and structural typing in TypeScript) let the consumer declare the interface it needs, so ISP and DIP happen naturally: the interface lives next to the code that uses it. Containers (Laravel, Spring, .NET) make DIP cheap to wire but also make it cheap to inject twenty dependencies into one class, which is an SRP smell the container hides.
Mechanics
Measuring dependency direction: instability and abstractness Important
Martin's 2000 paper defines three numbers per package:
| Metric | Definition | Range | Reading |
|---|---|---|---|
| Ca, afferent coupling | Classes outside the package that depend on classes inside it (incoming) | 0..n | High = many dependants; changes are expensive |
| Ce, efferent coupling | Classes outside the package that the package depends on (outgoing) | 0..n | High = many reasons to change from below |
| I, instability | Ce / (Ca + Ce) | 0..1 | 0 = maximally stable, 1 = maximally unstable |
| A, abstractness | Abstract classes / all classes (Na / Nc) | 0..1 | 1 = only interfaces |
| D′, distance from the main sequence | |A + I − 1| | 0..1 | 0 = balanced; near (0,0) is the "zone of pain", near (1,1) the "zone of uselessness" |
SDP says dependencies should point toward lower I; SAP says low-I packages should have high A. Together they are DIP at the package level: the stable centre is abstract, the unstable edge is concrete. Martin warns that the metrics "are imperfect, and reliance upon them as the sole indicator of a sturdy architecture would be foolhardy."
Seeing the graph in Go and Laravel Good to know
# Go: every package of the module with its imports
go list -f '{{.ImportPath}}: {{join .Imports " "}}' ./...
# Go: who imports package X (fan-in)
go list -f '{{.ImportPath}} {{join .Imports " "}}' ./... | grep ' academy/solid/srp/kata/after/employee'// Laravel: an architecture test (Pest) that keeps the arrows pointing inward.
arch('domain does not depend on the framework')
->expect('App\Domain')
->not->toUse(['Illuminate\Http', 'Illuminate\Support\Facades']);Change coupling: the history view Good to know
Static metrics show who can affect whom; version-control history shows who does. Files that change in the same commits are coupled whether or not one imports the other. The SRP chapter has the git + SQL recipe.
Critiques
SOLID has serious critics, and a practitioner should know their arguments.
Dan North, CUPID (2021–2022). In CUPID: the back story he describes a talk refuting each principle and finds that "the alternative kept turning out to be the same thing":
"Write simple code." — Dan North, CUPID: the back story, 2021
He calls SRP the "Pointlessly Vague Principle", argues that most dependencies "aren't options" and need no inverting, and proposes five properties instead of rules: Composable, Unix philosophy, Predictable, Idiomatic, Domain-based. Our reading: his critique hits the popular misreadings (SRP as "one thing", DIP as "inject everything") harder than Martin's own texts, and CUPID's properties are a good complement: SOLID asks how code changes, CUPID asks how it feels to use.
Casey Muratori, "Clean" Code, Horrible Performance (2023). He takes the rules most often taught alongside SOLID ("prefer polymorphism to if/else and switch", small functions, no internal knowledge) and measures a shape-area example in C++: replacing virtual calls with a switch made it about 1.5× faster, and further rule-breaking widened the gap to about 10× and then 15×. His article attacks "clean code" rules rather than SOLID by name, but it bears on how OCP is usually implemented. Our reading: polymorphism has a cost in hot loops over a closed set of types; OCP is strategic, so a performance-critical inner loop over a fixed set is a legitimate place for a switch (see the Expression Problem in OCP).
Go culture. "A little copying is better than a little dependency" (Go Proverbs) pushes back on reflexive extraction, which matches SRP's warning about accidental duplication.
| Critique | What it gets right | What it misses |
|---|---|---|
| "SRP is vague" (North) | "One thing" is meaningless | Martin's 2014 "one actor" is concrete |
| "Most dependencies need no inversion" (North) | Interfaces for every class are waste | Boundaries to I/O and other teams do need them |
| "Polymorphism is slow" (Muratori) | Virtual dispatch in hot loops costs | Most business code is I/O-bound; closure is strategic |
| "Principles are rules" (North) | Rule-following without judgement fails | Martin's texts are full of "strategic", "judgement", "probable" |
Solving the classic problems
| Symptom in the code | Underlying problem | Principle | Move | Chapter |
|---|---|---|---|---|
| A change for finance breaks the audit report | Two actors in one module | SRP | Extract Class by actor | SRP |
Every new variant edits the same switch | No abstraction at the point of variation | OCP | Replace Conditional with Polymorphism, registry | OCP |
Callers check instanceof / type switches on implementations | An implementation breaks the contract | LSP | Fix the contract or the hierarchy | LSP |
| Fakes in tests implement 20 methods to use 2 | Fat interface | ISP | Split into role interfaces | ISP |
| Business logic cannot be tested without a database | Policy depends on a detail | DIP | Interface owned by the policy; wire in main / provider | DIP |
| Teams block each other's deploys | Module borders do not match team borders | SRP + Conway's law | Modules per team, CODEOWNERS | SRP |
One example that touches all five:
// Policy owns the interfaces it needs (DIP, ISP); new gateways are new types (OCP);
// every gateway must honour Charge's contract (LSP); checkout answers to one actor (SRP).
package checkout
type Charger interface {
Charge(ctx context.Context, orderID string, cents int64) (ref string, err error)
}
type Service struct{ pay Charger }
func (s Service) Pay(ctx context.Context, orderID string, cents int64) (string, error) {
if cents <= 0 {
return "", errors.New("checkout: amount must be positive")
}
return s.pay.Charge(ctx, orderID, cents)
}// The same in Laravel: the contract lives with the policy; the provider binds the detail.
interface Charger
{
public function charge(string $orderId, int $cents): string;
}
final class PayOrder
{
public function __construct(private Charger $charger) {}
public function handle(Order $order): string
{
return $this->charger->charge((string) $order->id, $order->total_cents);
}
}
// AppServiceProvider::register(): $this->app->bind(Charger::class, StripeCharger::class);Choosing: which principle for which situation
| Situation | Principle to reach for | Technique | Reason |
|---|---|---|---|
| Several teams edit one class or package | SRP | Split by actor | Different reasons to change |
| A set of variants keeps growing | OCP | Interface at the point of variation, registry | New variants become additions |
| You add an implementation and callers break | LSP | Contract tests for every implementation | Substitution must be safe |
| Test doubles are painful | ISP | Consumer-defined role interfaces | Depend only on what you use |
| Business rules import the ORM or SDK | DIP | Ports owned by the policy, adapters outside | Policy must not change with details |
| One team, small app, one variant | None yet | Write direct code | Abstractions cost; wait for evidence |
| Hot loop over a closed set of types | None | switch, measure | Performance; closure is strategic |
| Public API or event schema | OCP + LSP | Additive changes, versioning | Clients cannot be edited |
In architecture: from a single process to a distributed system
The principles were written for classes, but each has a system-level form. Martin's 2012 Dependency Rule is DIP for a whole application; bounded contexts and team topologies are SRP with a network boundary; webhooks and event topics are OCP between organisations; API compatibility is LSP across versions.
Monolith: one process, one database
How it shows up: classes, packages and the framework's slots. The composition root (main in Go, service providers in Laravel) is where DIP's wiring lives.
Example (simple): a Laravel shop where controllers call Actions, Actions depend on contracts (Charger, OrderStore), and AppServiceProvider binds them.
Example (complex): a Go monolith with internal/pricing, internal/orders, internal/postgres, internal/httpapi and cmd/api; the import graph is acyclic (ADP, enforced by the compiler) and points from adapters to policy (DIP).
Modular monolith and multiple databases
How it shows up: each module has a facade (SRP), publishes in-process events (OCP), owns its interfaces (DIP), and owns its tables.
-- PostgreSQL: one schema per module; other modules may read only through views the owner publishes.
CREATE SCHEMA orders;
CREATE VIEW orders.public_order_totals AS SELECT id, user_id, total_cents FROM orders.orders;
GRANT SELECT ON orders.public_order_totals TO billing_app; -- a stable, narrow contract (ISP)Microservices
What survives: SRP becomes "one team per service"; OCP becomes "publish events, let consumers subscribe"; LSP becomes "every version of the API keeps the old promises"; ISP becomes "consumer-specific endpoints or schemas instead of one giant payload"; DIP becomes "services depend on contracts (OpenAPI, AsyncAPI, schema registry), not on each other's internals".
Checkout service Broker Consumers
1 BEGIN; INSERT order; INSERT outbox; COMMIT
2 relay publishes OrderPlaced v1 -> topic orders invoicing, fulfilment
3 (unchanged) (unchanged) + loyalty subscribes (OCP)
4 adds optional field giftWrap v1.1 old consumers unaffected (LSP)See Event-Driven Architecture and Transactional Outbox.
Distributed data: replicas, caches and shared stores
Where the principles break: a shared database couples every service to every schema (SRP and DIP violated at once); a shared Redis cache with no key ownership has many reasons to change; a read replica queried ad hoc by every team turns the schema into an unversioned public API. Countermeasures: one owner per table and key prefix, published read models, change data capture instead of cross-service reads, schema compatibility rules.
Scaling path: 1×, 10×, 100×
| Scale | Structure | How SOLID shows up |
|---|---|---|
| 1× (one team) | Folders by feature, framework slots | Direct code first; abstract at boundaries to I/O and on the third variant |
| 10× (several teams, one repo) | Modular monolith | Module facades, consumer-owned interfaces, architecture tests, CODEOWNERS |
| 100× (many teams and services) | Services per capability | Contracts, events, versioned APIs, schema registries, team ownership |
The Design path
The Design section of this site is a learning path of 27 chapters in five groups (overview). SOLID is group three: it rests on the design-quality vocabulary of group two (coupling, cohesion, information hiding) and is the toolkit the pattern chapters of group four use. "Live" chapters are published (the path overview shows which are complete and which are being deepened); "Upcoming" chapters have a placeholder page and are being written.
| # | Group | Chapter | Status | Link to SOLID |
|---|---|---|---|---|
| 01 | DZ 01 · Foundations | Software Architecture vs Software Design | Upcoming | |
| 02 | DZ 01 · Foundations | The Design Process | Upcoming | |
| 03 | DZ 01 · Foundations | Quality Attributes & Requirements | Upcoming | |
| 04 | DZ 01 · Foundations | Object-Oriented Modeling | Upcoming | |
| 05 | DZ 01 · Foundations | UML in Practice | Upcoming | |
| 06 | DZ 02 · Design Quality | Design Quality: Coupling & Cohesion, Information Hiding | Upcoming | Coupling and cohesion in depth (the roots of SRP) |
| 07 | DZ 02 · Design Quality | Composing Objects & the Law of Demeter | Upcoming | |
| 08 | DZ 02 · Design Quality | Code Smells, Anti-Patterns & Refactoring | Upcoming | Speculative generality, shotgun surgery, divergent change and their moves |
| 09 | DZ 02 · Design Quality | Low-Level Design | Upcoming | |
| 10 | DZ 03 · SOLID | SOLID overview (this page) | Live | History, vocabulary, the one argument |
| 11 | DZ 03 · SOLID | Single Responsibility | Live | SRP: actors, cohesion, coupling, change coupling |
| 12 | DZ 03 · SOLID | Open–Closed | Live | OCP: extension points, plugins, when to abstract |
| 13 | DZ 03 · SOLID | Liskov Substitution | Live | Contracts and substitutability |
| 14 | DZ 03 · SOLID | Interface Segregation | Live | Role interfaces |
| 15 | DZ 03 · SOLID | Dependency Inversion | Live | Ports, adapters, composition roots |
| 16 | DZ 04 · Design Patterns | Design Patterns: Introduction | Upcoming | |
| 17 | DZ 04 · Design Patterns | Creational Patterns | Upcoming | Factories and the composition root |
| 18 | DZ 04 · Design Patterns | Structural Patterns | Upcoming | Facade, Adapter, Decorator as SOLID tools |
| 19 | DZ 04 · Design Patterns | Behavioral Patterns | Upcoming | Strategy, Observer, Visitor (the Expression Problem) |
| 20 | DZ 04 · Design Patterns | Applying Patterns in Real Systems | Upcoming | |
| 21 | DZ 05 · Key Design Issues | Designing for Concurrency | Upcoming | |
| 22 | DZ 05 · Key Design Issues | Control Flow & Event Handling | Upcoming | |
| 23 | DZ 05 · Key Design Issues | Data Persistence in Design | Upcoming | Repositories: DIP and SRP at the storage boundary |
| 24 | DZ 05 · Key Design Issues | Distribution of Components | Upcoming | |
| 25 | DZ 05 · Key Design Issues | Error Handling & Fault Tolerance | Upcoming | |
| 26 | DZ 05 · Key Design Issues | Interaction & Presentation: MVC, MVP, MVVM | Upcoming | |
| 27 | DZ 05 · Key Design Issues | Security by Design | Upcoming |
Reading order. Read SRP → OCP → LSP → ISP → DIP in order; each assumes the previous. If you want the idea the other four lean on, start with Dependency Inversion and come back. Readers coming from the database or messaging sections will find the bridges in each chapter's architecture section.
Lab
Measure your own Go module, then run the two katas.
Step 1: dump the internal import graph.
cd docs/snippets/solid/go # or your own module
go list -f '{{range .Imports}}{{$.ImportPath}},{{.}}{{"\n"}}{{end}}' ./... \
| grep ',academy/' > edges.csv
sqlite3 graph.db '.mode csv' 'CREATE TABLE edges(src TEXT, dst TEXT);' '.import edges.csv edges'Step 2: compute Ca, Ce and instability per package.
WITH pkgs AS (SELECT src AS p FROM edges UNION SELECT dst FROM edges),
ca AS (SELECT dst AS p, COUNT(*) AS ca FROM edges GROUP BY dst),
ce AS (SELECT src AS p, COUNT(*) AS ce FROM edges GROUP BY src)
SELECT pkgs.p,
COALESCE(ca.ca, 0) AS ca,
COALESCE(ce.ce, 0) AS ce,
ROUND(1.0 * COALESCE(ce.ce, 0) / NULLIF(COALESCE(ca.ca, 0) + COALESCE(ce.ce, 0), 0), 2) AS instability
FROM pkgs LEFT JOIN ca USING (p) LEFT JOIN ce USING (p)
ORDER BY instability;
-- academy/solid/ocp/registry/notify | 3 | 0 | 0.0 (stable core: email, sms, app import it)
-- academy/solid/srp/kata/after/employee | 3 | 0 | 0.0 (stable data)
-- academy/solid/ocp/registry/app | 0 | 3 | 1.0 (composition root: unstable by design)Step 3: check the arrows. Expected: every arrow points from high instability (adapters, app, cmd) to low instability (policy, data). Any arrow from a stable package to an unstable one is an SDP/DIP violation.
Step 4: run the SRP kata in the SRP chapter lab: expected result, a pay-rule change touches 1 file and 1 actor instead of 2 actors.
Step 5: run the OCP kata in the OCP chapter lab: expected result, adding a channel changes 0 lines in the core instead of 5.
Step 6: try one critique. Take the OCP kata's registry and ask North's question: does it "fit in my head"? If the system will only ever have two channels, the switch version may be the better code. Write down which you would ship and why.
Common misconceptions
| Belief | Reality |
|---|---|
| SOLID was introduced in Martin's 2000 paper | The paper has four of the five; SRP is named in the 2002 book; the acronym dates from about 2004 |
| Martin invented all five | OCP is Meyer's, LSP is Liskov's; Martin articulated SRP, ISP and DIP and connected them |
| SOLID is only for OOP | It is about dependencies; Cheney maps it to Go packages and interfaces |
| More interfaces = more SOLID | Abstractions cost; closure is strategic |
| DIP = dependency injection container | Injection is a technique; DIP is ownership and direction |
| SRP = do one thing | SRP = one reason to change, i.e. one actor |
| The order S-O-L-I-D matters | It was rearranged to spell a word |
| SOLID guarantees good design | It addresses dependency rot; it says nothing about algorithms, data or performance |
| Following SOLID has no runtime cost | Indirection can cost in hot loops (Muratori's measurements) |
| SOLID stops at the class | Package principles, the Dependency Rule and service boundaries carry it to systems |
Cheat sheet
| Topic | Remember |
|---|---|
| One question | When requirements change, how much code changes with them? |
| One answer | Control the direction and size of dependencies |
| S | One actor per module; gather what changes together |
| O | Add code, not edits, for expected changes; closure is strategic |
| L | Implementations keep every promise of the abstraction |
| I | Interfaces shaped by their clients |
| D | Policy owns abstractions; details implement them; wire in the composition root |
| Rot symptoms | Rigidity, fragility, immobility, viscosity |
| Package metrics | I = Ce/(Ca+Ce); A = Na/Nc; D′ = |A+I−1| |
| Go | Package = unit of change; small consumer-side interfaces; main wires |
| Laravel | Framework slots for SRP; contracts + container + providers for OCP/DIP |
| Critiques | CUPID (write simple code), Muratori (cost of polymorphism), "a little copying" |
| Systems | Dependency Rule, bounded contexts, events, versioned contracts |
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 — Who suggested the name SOLID, and roughly when? Good to know
Answer
Answer: Michael Feathers, in an email to Martin; Martin recalls "I think it was 2004". See Where it comes from.
2 — Which principle is missing from Martin's 2000 paper, and what is its closest relative there? Good to know
Answer
Answer: SRP. The Common Closure Principle, "Classes that change together, belong together." See A correction.
3 — Explain in three sentences how the five principles form one argument. Important
Answer
Answer: DIP makes policy depend on abstractions it owns; OCP lets new behaviour arrive as new implementations; LSP makes those implementations safe to substitute, ISP keeps the abstractions client-sized and SRP draws module borders by actor. See One argument.
4 — Name Martin's four symptoms of design rot. Must-know
Answer
Answer: Rigidity, fragility, immobility, viscosity. See Everything in one minute.
5 — Why do Go's implicit interfaces make ISP and DIP easier than in Java? Important
Answer
Answer: The consumer can declare the small interface it needs next to its own code; any type with the methods satisfies it without naming it, so the abstraction is owned by the policy. See SOLID across languages.
6 — A package has Ca = 0 and Ce = 4. What is its instability, and is that bad? Important
Answer
Answer: I = 4 / (0 + 4) = 1, maximally unstable. It is fine for a composition root or an adapter; bad if other packages are supposed to depend on it. See Mechanics.
7 — What is the Dependency Rule of Clean Architecture, and which SOLID principle does it scale up? Must-know
Answer
Answer: Source-code dependencies can only point inwards, toward higher-level policy. It is DIP applied to a whole system. See Where it comes from.
8 — What does Dan North propose instead of SOLID, and what is his core advice? Good to know
Answer
Answer: CUPID: Composable, Unix philosophy, Predictable, Idiomatic, Domain-based properties; core advice "Write simple code." See Critiques.
9 — When is a switch over types a better design than an interface? Important
Answer
Answer: When the set of types is closed and stable, especially in a hot loop: new operations are cheap, dispatch is fast. OCP is strategic. See Critiques and OCP.
10 — What are the microservice-level forms of SRP and OCP? Important
Answer
Answer: SRP: one team and one business capability per service. OCP: publish events so new consumers subscribe without changing the publisher, and evolve APIs additively. See Microservices.
Glossary
| Term | Meaning |
|---|---|
| SOLID | Acronym for SRP, OCP, LSP, ISP, DIP, suggested by Michael Feathers around 2004 |
| Single Responsibility Principle (SRP) | One reason to change (one actor) per module |
| Open–Closed Principle (OCP) | Open for extension, closed for modification |
| Liskov Substitution Principle (LSP) | Subtypes keep the behaviour promised by their supertype |
| Interface Segregation Principle (ISP) | Clients depend only on methods they use |
| Dependency Inversion Principle (DIP) | Policy and details both depend on abstractions owned by the policy |
| Reason to change / actor | The group of people whose requests change a module |
| Coupling | How much changing one module forces changing another |
| Cohesion | How strongly a module's parts belong together |
| Information hiding | Parnas: each module hides a design decision likely to change |
| Abstraction | An interface or contract that hides which implementation is used |
| Point of variation | Where variants differ; where an OCP abstraction belongs |
| Strategic closure | Choosing which changes a module is closed against |
| Contract (behavioural) | Preconditions, postconditions and invariants an implementation must keep |
| Role interface | A small interface shaped by one client's needs |
| Composition root | The one place that wires concrete implementations (main, service providers) |
| Dependency injection | Passing dependencies in from outside; a technique for DIP |
| Service container | A runtime that resolves and injects dependencies (Laravel, Spring, .NET) |
| Dependency Rule | Clean Architecture: source dependencies point inward only |
| Plugin architecture | Core owns interfaces; plugins depend on the core |
| Design rot | Rigidity, fragility, immobility, viscosity (Martin 2000) |
| Rigidity / Fragility / Immobility / Viscosity | Hard to change / breaks elsewhere / hard to reuse / hacks easier than the right fix |
| REP, CCP, CRP | Package cohesion principles: release = reuse, change together, reuse together |
| ADP, SDP, SAP | Package coupling principles: no cycles, depend toward stability, stable = abstract |
| Afferent / efferent coupling (Ca / Ce) | Incoming / outgoing dependencies of a package |
| Instability (I) | Ce / (Ca + Ce) |
| Abstractness (A) | Abstract types / all types in a package |
| Main sequence / D′ | The line A + I = 1; distance from it |
| Change coupling | Files that change together in version-control history |
| Conway's law | Systems copy the organisation's communication structure |
| Protected Variations | Larman's name for OCP: stable interfaces around predicted variation |
| Expression Problem | Types vs operations: no common design makes both cheap |
| CUPID | Dan North's properties: Composable, Unix philosophy, Predictable, Idiomatic, Domain-based |
| Speculative generality | Abstractions added before any real need |
| Bounded context | DDD boundary for one consistent model; SRP at system scale |
References
- Robert C. Martin, Design Principles and Design Patterns (2000). PDF mirror
- Robert C. Martin, Engineering Notebook columns, The C++ Report (1996): OCP, DIP, ISP
- Robert C. Martin, "SRP: The Single Responsibility Principle", chapter draft of Agile Software Development (2002). Object Mentor PDF, archived
- Robert C. Martin, "The Clean Architecture" (2012). blog.cleancoder.com
- Robert C. Martin, "The Single Responsibility Principle" (2014). blog.cleancoder.com
- Robert C. Martin, "The Open Closed Principle" (2014). blog.cleancoder.com
- Wesley Reisz, "Uncle Bob Martin on Clean Software, Craftsperson, Origins of SOLID, DDD, & Software Ethics", InfoQ podcast (2018). infoq.com
- Barbara Liskov, "Data Abstraction and Hierarchy", OOPSLA '87 (1987). PDF; Liskov & Wing, "A Behavioral Notion of Subtyping", ACM TOPLAS (1994). PDF
- D. L. Parnas, "On the Criteria To Be Used in Decomposing Systems into Modules" (1972). PDF
- W. P. Stevens, G. J. Myers, L. L. Constantine, "Structured Design", IBM Systems Journal (1974). PDF copy
- Melvin E. Conway, "How Do Committees Invent?" (1968). melconway.com
- Craig Larman, "Protected Variation: The Importance of Being Closed", IEEE Software (2001). PDF
- Dave Cheney, "SOLID Go Design" (2016). dave.cheney.net; Rob Pike, Go Proverbs
- Dan North, "CUPID: the back story" (2021). dannorth.net; "CUPID: for joyful coding" (2022). dannorth.net
- Casey Muratori, ""Clean" Code, Horrible Performance" (2023). computerenhance.com
- Laravel 13 documentation: Service Container, Contracts, Service Providers
- PHP-FIG, PSR-11: Container interface