Skip to content

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 forGo to
The five principles on one screenEverything in one minute
What problem SOLID solvesWhy SOLID exists
1972 → 2004 → today, with primary sourcesWhere it comes from
Each principle in plain words, with its usual misreadingThe principles, one by one
How the five fit togetherOne argument: dependency direction
Go vs PHP vs Java vs C# vs TypeScript vs PythonSOLID across languages
Measuring dependencies: instability, abstractness, change couplingMechanics
CUPID, performance, "a little copying"Critiques
Which principle for which symptomSolving the classic problems, Choosing
SOLID from a monolith to microservicesIn architecture
The Design path and reading orderThe Design path
A lab that measures your own codebaseLab
Wrong beliefs, cheat sheet, self-check, all SOLID termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The five principles.

LetterPrincipleThe one-line rule (original wording where it exists)Plain wordsOriginal source
SSingle Responsibility"THERE SHOULD NEVER BE MORE THAN ONE REASON FOR A CLASS TO CHANGE."One module answers to one group of peopleMartin, Agile Software Development (2002); "about people" in his 2014 post
OOpen–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 codeMeyer (1988); Martin, C++ Report (1996)
LLiskov SubstitutionSubtypes must be usable through the base type without the caller noticingA plug-in must keep the promises of the socketLiskov, OOPSLA keynote (1987); Liskov & Wing (1994); Martin (March 1996)
IInterface SegregationClients should not be forced to depend on interfaces they do not useSmall, role-shaped interfacesMartin, C++ Report (1996)
DDependency 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 inMartin, C++ Report (May 1996)

What design rot looks like (Martin's 2000 paper names four symptoms; SOLID is the treatment).

SymptomMartin's description, shortenedTypical causePrinciple that helps most
RigidityEvery change causes a cascade of changes in dependent modulesDependencies on concrete detailsDIP, OCP
FragilitySoftware breaks in places with no conceptual relationship to the changeSeveral actors in one moduleSRP, LSP
ImmobilityUseful parts cannot be reused without dragging everything alongPolicy tangled with detailsDIP, ISP
ViscosityDoing the right thing is harder than the hackAbstractions that fight the changeOCP, SRP

The one-sentence version.

If you remember one thingIt is this
What SOLID is aboutControlling the direction and size of dependencies
What it is notRules of syntax, class counts, or a requirement to use inheritance
How to apply itAsk "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 principlesCode with the principles
Fewer types, fewer files at the startMore types and files, each with a clear owner
Policy calls the database, the HTTP client and the mailer directlyPolicy calls small interfaces it owns; details plug in
A new requirement edits working codeA new requirement mostly adds code
Tests need the whole stackRules are tested in memory
Fast to write the first versionFaster to change the twentieth version
Risk: rotRisk: 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 ​

  1. "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.
  2. "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.
  3. "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 ​

1968 / 1972Conway's law;Parnas: hiding1974Stevens, Myers,Constantine1987 / 1988Liskov keynote;Meyer: OCP1996C++ Report: OCP,LSP, DIP, ISP2000Principles andPatterns paper2002Agile SoftwareDev.: SRP chapter2004Feathers: theword SOLID2012Clean ArchitectureDependency Rule2014SRP "about people";OCP = plugins2016Cheney: SOLIDGo Design2021 / 2022 / 2023North: CUPID;Muratori: costroots and other authors (grey) · Martin's texts (brand) · critiques (red)

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.

YearEventWhat it addedSource we read
1968Conway, How Do Committees Invent?Systems copy the communication structure of their organisationmelconway.com
1972Parnas, On the Criteria To Be Used in Decomposing Systems into ModulesInformation hiding: each module hides a decision likely to changeCACM paper (PDF)
1974Stevens, Myers, Constantine, Structured DesignCoupling and cohesion ("binding") as measuresIBM Systems Journal reprint
1987Liskov, Data Abstraction and Hierarchy (OOPSLA keynote)The substitution propertySee LSP
1988Meyer, Object-Oriented Software Construction"open and closed" modulesVia Martin 1996 and 2014
1996Martin's Engineering Notebook columns in The C++ ReportOCP (his first column), LSP (March), DIP (May), ISP (the column after DIP)Duke course PDFs
2000Martin, Design Principles and Design PatternsFour class principles (OCP, LSP, DIP, ISP), six package principles, the rot symptoms; no SRP yetPDF
2002Martin, Agile Software Development: Principles, Patterns, and PracticesSRP chapter: "never more than one reason for a class to change"Object Mentor chapter draft
2004Michael Feathers rearranges the initialsThe word SOLIDInfoQ 2018
2012Martin, The Clean ArchitectureThe Dependency Rule for whole systemscleancoder blog
2014Martin's SRP and OCP postsSRP "is about people"; OCP's apotheosis is the plugincleancoder blog
2016Cheney, SOLID Go DesignSOLID without classesdave.cheney.net
2021–2022Dan North, CUPIDA critique and an alternative set of propertiesdannorth.net
2023Muratori, "Clean" Code, Horrible PerformanceThe runtime cost of polymorphism-first rulescomputerenhance.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."

text
     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 unchanged

Real 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.

text
     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)       no

Real 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."

text
     Caller                         FileStore            ReadOnlyStore (violates LSP)
1    store.Save(doc)                ok                   panics "read only"
2    caller adds `if store is ReadOnlyStore` checks -> OCP lost as well

Real 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."

text
     Change                               Fat Repository interface         Role interfaces
1    add BulkExport() for analytics       every fake and every client      only the Exporter role
                                          recompiles / updates

Real 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)

text
     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:

PrincipleWording in the 2000 paperConcern
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 ReuseClasses that are not reused together should not be grouped togetherCohesion: ISP for packages
ADP, Acyclic DependenciesNo cycles in the package dependency graphCoupling (Go's compiler enforces it)
SDP, Stable Dependencies"Depend in the direction of stability."Coupling
SAP, Stable AbstractionsStable packages should be abstractCoupling: DIP for packages

Fix: measure them with the instability and abstractness metrics.

One argument: dependency direction ​

Business policy (one actor each)SRP draws these bordersOrderStoreinterfacePaymentGatewayinterfaceHTTP handlerLaravel controller / net/httpPostgreSQL repositoryimplements OrderStoreMongoDB repositoryLSP: must keep the promisesQueue workerLaravel job / Go consumerStripe gatewayimplements PaymentGatewayNew gateway (OCP)added, nothing editedISP: interfaces sized to the policy's needsDIP: every arrow points inwardDetails depend on policy; policy depends on nothing it does not own.

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.

  1. 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.
  2. OCP explains why that pays: a policy that depends on a fixed abstraction can gain behaviour by adding implementations, without being edited.
  3. 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.
  4. 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.
  5. SRP draws the borders: each module answers to one actor, so a request from one actor lands in one place.
text
     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 ​

PrincipleGoPHP / LaravelJava / SpringC# / .NETTypeScriptPython
SRP unitPackage (Cheney: "a single unit of change")Class + framework slot (Form Request, Action, Policy, Job)Class + package / moduleClass + assemblyES moduleModule / package
OCP mechanismSmall interfaces, Register + init(), embedding, genericsContracts + container, Manager::extend, eventsInterfaces, autowired collections, ServiceLoaderInterfaces, DI with multiple or keyed registrationsStructural interfaces, plugin arraysProtocols/ABCs, entry points, singledispatch
LSP checkBehavioural contract tests; no inheritance to abuseContract tests; return-type covariance rules in PHPContract tests; inheritance makes violations easySame as JavaStructural typing checks shape, not behaviourDuck typing checks nothing at definition time
ISP shapeOne-method interfaces (io.Reader); defined by the consumerNarrow contracts; role interfacesRole interfaces; default methods blur itRole interfacesPick<T, K>, small interfacestyping.Protocol per role
DIP wiringManual in main (composition root)Service container, service providersSpring IoC containerMicrosoft.Extensions.DependencyInjectionManual or a DI libraryManual or a DI library
Typical violationpackage utils; 20-method interfaces copied from JavaFat controller, god model, new inside servicesAnaemic services with everything injectedSame as JavaBarrel files that import everythingGod 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:

MetricDefinitionRangeReading
Ca, afferent couplingClasses outside the package that depend on classes inside it (incoming)0..nHigh = many dependants; changes are expensive
Ce, efferent couplingClasses outside the package that the package depends on (outgoing)0..nHigh = many reasons to change from below
I, instabilityCe / (Ca + Ce)0..10 = maximally stable, 1 = maximally unstable
A, abstractnessAbstract classes / all classes (Na / Nc)0..11 = only interfaces
D′, distance from the main sequence|A + I − 1|0..10 = 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 ​

bash
# 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'
php
// 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.

CritiqueWhat it gets rightWhat it misses
"SRP is vague" (North)"One thing" is meaninglessMartin's 2014 "one actor" is concrete
"Most dependencies need no inversion" (North)Interfaces for every class are wasteBoundaries to I/O and other teams do need them
"Polymorphism is slow" (Muratori)Virtual dispatch in hot loops costsMost business code is I/O-bound; closure is strategic
"Principles are rules" (North)Rule-following without judgement failsMartin's texts are full of "strategic", "judgement", "probable"

Solving the classic problems ​

Symptom in the codeUnderlying problemPrincipleMoveChapter
A change for finance breaks the audit reportTwo actors in one moduleSRPExtract Class by actorSRP
Every new variant edits the same switchNo abstraction at the point of variationOCPReplace Conditional with Polymorphism, registryOCP
Callers check instanceof / type switches on implementationsAn implementation breaks the contractLSPFix the contract or the hierarchyLSP
Fakes in tests implement 20 methods to use 2Fat interfaceISPSplit into role interfacesISP
Business logic cannot be tested without a databasePolicy depends on a detailDIPInterface owned by the policy; wire in main / providerDIP
Teams block each other's deploysModule borders do not match team bordersSRP + Conway's lawModules per team, CODEOWNERSSRP

One example that touches all five:

go
// 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)
}
php
// 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 ​

SituationPrinciple to reach forTechniqueReason
Several teams edit one class or packageSRPSplit by actorDifferent reasons to change
A set of variants keeps growingOCPInterface at the point of variation, registryNew variants become additions
You add an implementation and callers breakLSPContract tests for every implementationSubstitution must be safe
Test doubles are painfulISPConsumer-defined role interfacesDepend only on what you use
Business rules import the ORM or SDKDIPPorts owned by the policy, adapters outsidePolicy must not change with details
One team, small app, one variantNone yetWrite direct codeAbstractions cost; wait for evidence
Hot loop over a closed set of typesNoneswitch, measurePerformance; closure is strategic
Public API or event schemaOCP + LSPAdditive changes, versioningClients 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.

sql
-- 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".

text
     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× ​

ScaleStructureHow SOLID shows up
1× (one team)Folders by feature, framework slotsDirect code first; abstract at boundaries to I/O and on the third variant
10× (several teams, one repo)Modular monolithModule facades, consumer-owned interfaces, architecture tests, CODEOWNERS
100× (many teams and services)Services per capabilityContracts, 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.

#GroupChapterStatusLink to SOLID
01DZ 01 · FoundationsSoftware Architecture vs Software DesignUpcoming
02DZ 01 · FoundationsThe Design ProcessUpcoming
03DZ 01 · FoundationsQuality Attributes & RequirementsUpcoming
04DZ 01 · FoundationsObject-Oriented ModelingUpcoming
05DZ 01 · FoundationsUML in PracticeUpcoming
06DZ 02 · Design QualityDesign Quality: Coupling & Cohesion, Information HidingUpcomingCoupling and cohesion in depth (the roots of SRP)
07DZ 02 · Design QualityComposing Objects & the Law of DemeterUpcoming
08DZ 02 · Design QualityCode Smells, Anti-Patterns & RefactoringUpcomingSpeculative generality, shotgun surgery, divergent change and their moves
09DZ 02 · Design QualityLow-Level DesignUpcoming
10DZ 03 · SOLIDSOLID overview (this page)LiveHistory, vocabulary, the one argument
11DZ 03 · SOLIDSingle ResponsibilityLiveSRP: actors, cohesion, coupling, change coupling
12DZ 03 · SOLIDOpen–ClosedLiveOCP: extension points, plugins, when to abstract
13DZ 03 · SOLIDLiskov SubstitutionLiveContracts and substitutability
14DZ 03 · SOLIDInterface SegregationLiveRole interfaces
15DZ 03 · SOLIDDependency InversionLivePorts, adapters, composition roots
16DZ 04 · Design PatternsDesign Patterns: IntroductionUpcoming
17DZ 04 · Design PatternsCreational PatternsUpcomingFactories and the composition root
18DZ 04 · Design PatternsStructural PatternsUpcomingFacade, Adapter, Decorator as SOLID tools
19DZ 04 · Design PatternsBehavioral PatternsUpcomingStrategy, Observer, Visitor (the Expression Problem)
20DZ 04 · Design PatternsApplying Patterns in Real SystemsUpcoming
21DZ 05 · Key Design IssuesDesigning for ConcurrencyUpcoming
22DZ 05 · Key Design IssuesControl Flow & Event HandlingUpcoming
23DZ 05 · Key Design IssuesData Persistence in DesignUpcomingRepositories: DIP and SRP at the storage boundary
24DZ 05 · Key Design IssuesDistribution of ComponentsUpcoming
25DZ 05 · Key Design IssuesError Handling & Fault ToleranceUpcoming
26DZ 05 · Key Design IssuesInteraction & Presentation: MVC, MVP, MVVMUpcoming
27DZ 05 · Key Design IssuesSecurity by DesignUpcoming

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.

bash
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.

sql
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 ​

BeliefReality
SOLID was introduced in Martin's 2000 paperThe paper has four of the five; SRP is named in the 2002 book; the acronym dates from about 2004
Martin invented all fiveOCP is Meyer's, LSP is Liskov's; Martin articulated SRP, ISP and DIP and connected them
SOLID is only for OOPIt is about dependencies; Cheney maps it to Go packages and interfaces
More interfaces = more SOLIDAbstractions cost; closure is strategic
DIP = dependency injection containerInjection is a technique; DIP is ownership and direction
SRP = do one thingSRP = one reason to change, i.e. one actor
The order S-O-L-I-D mattersIt was rearranged to spell a word
SOLID guarantees good designIt addresses dependency rot; it says nothing about algorithms, data or performance
Following SOLID has no runtime costIndirection can cost in hot loops (Muratori's measurements)
SOLID stops at the classPackage principles, the Dependency Rule and service boundaries carry it to systems

Cheat sheet ​

TopicRemember
One questionWhen requirements change, how much code changes with them?
One answerControl the direction and size of dependencies
SOne actor per module; gather what changes together
OAdd code, not edits, for expected changes; closure is strategic
LImplementations keep every promise of the abstraction
IInterfaces shaped by their clients
DPolicy owns abstractions; details implement them; wire in the composition root
Rot symptomsRigidity, fragility, immobility, viscosity
Package metricsI = Ce/(Ca+Ce); A = Na/Nc; D′ = |A+I−1|
GoPackage = unit of change; small consumer-side interfaces; main wires
LaravelFramework slots for SRP; contracts + container + providers for OCP/DIP
CritiquesCUPID (write simple code), Muratori (cost of polymorphism), "a little copying"
SystemsDependency Rule, bounded contexts, events, versioned contracts

Self-check: questions & answers ​

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

1 — 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 ​

TermMeaning
SOLIDAcronym 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 / actorThe group of people whose requests change a module
CouplingHow much changing one module forces changing another
CohesionHow strongly a module's parts belong together
Information hidingParnas: each module hides a design decision likely to change
AbstractionAn interface or contract that hides which implementation is used
Point of variationWhere variants differ; where an OCP abstraction belongs
Strategic closureChoosing which changes a module is closed against
Contract (behavioural)Preconditions, postconditions and invariants an implementation must keep
Role interfaceA small interface shaped by one client's needs
Composition rootThe one place that wires concrete implementations (main, service providers)
Dependency injectionPassing dependencies in from outside; a technique for DIP
Service containerA runtime that resolves and injects dependencies (Laravel, Spring, .NET)
Dependency RuleClean Architecture: source dependencies point inward only
Plugin architectureCore owns interfaces; plugins depend on the core
Design rotRigidity, fragility, immobility, viscosity (Martin 2000)
Rigidity / Fragility / Immobility / ViscosityHard to change / breaks elsewhere / hard to reuse / hacks easier than the right fix
REP, CCP, CRPPackage cohesion principles: release = reuse, change together, reuse together
ADP, SDP, SAPPackage 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 couplingFiles that change together in version-control history
Conway's lawSystems copy the organisation's communication structure
Protected VariationsLarman's name for OCP: stable interfaces around predicted variation
Expression ProblemTypes vs operations: no common design makes both cheap
CUPIDDan North's properties: Composable, Unix philosophy, Predictable, Idiomatic, Domain-based
Speculative generalityAbstractions added before any real need
Bounded contextDDD 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

Built by Morteza Negahi