Skip to content

Single Responsibility Principle (SRP) ​

"The Single Responsibility Principle (SRP) states that each software module should have one and only one reason to change." — Robert C. Martin, The Single Responsibility Principle, The Clean Code Blog, 8 May 2014

Summary: SRP says a module should answer to one source of change: one person, team or business function. It is about who asks for changes, not about how many methods a class has. Focus: Reason to change, actors, cohesion and coupling, accidental duplication, god classes, packages as units of change, Conway's law, metrics (LCOM, CBO, change coupling) and the refactoring moves that fix violations, in Go and Laravel. Learning goal: Look at a module, name the actors who change it, measure whether they collide, and split or merge it with Extract Class and Move Method until each change request touches one place.

This page is the complete reference for the first SOLID principle. It covers the history (Parnas 1972, Stevens, Myers and Constantine 1974, Martin's 2002 chapter and 2014 post), every term practitioners use around it, how to measure it from code and from git history, how Go and Laravel give each responsibility a home, and what SRP means once a "module" is a service owned by a team. It does not re-teach its neighbours: the overview and the history of the acronym are on SOLID, extension points are on Open–Closed, substitutability is on Liskov Substitution, small interfaces are on Interface Segregation, and the direction of dependencies is on Dependency Inversion.

Page map ​

If you are looking forGo to
The whole principle in a few tablesEverything in one minute
Why SRP exists and what it tradesWhy SRP exists
Parnas, Constantine, Martin's 2002 and 2014 wordingWhere it comes from
Reason to change, actor, cohesion, coupling, accidental duplication, god class, fan-in/fan-outThe concepts, one by one
How Go, Laravel, Spring, .NET, TypeScript and Python express SRPPer-language and per-framework view
LCOM, CBO, change coupling from git, refactoring movesMechanics
Before/after code in Go and LaravelGo, Laravel
Fat controller, god model, utils package, shared helperSolving the classic problems
When to split and when to mergeChoosing
Modular monolith, microservices, team ownershipIn architecture
A kata with before/after numbersLab: refactoring kata
Wrong beliefs, cheat sheet, self-check, every termMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The vocabulary. Every row is unpacked in the concepts section.

TermIn plain wordsTiny exampleWhat goes wrong without it
Reason to changeA source of change requests"Finance changed the overtime rule"One request breaks an unrelated feature
Actor (stakeholder group)The people who want the same changeCFO's payroll teamTwo actors edit one file and collide
CohesionHow strongly the parts of a module belong togetherpayroll package: only pay rulesutils grows into a junk drawer
CouplingHow much a change in one module forces a change in anotherReport breaks when pay rule changesFragile code, "I only touched X" bugs
Accidental duplicationCode that looks the same today but changes for different reasonsPay and audit both count "regular hours"Merging it couples two actors
God classOne class that every actor edits3,000-line User modelMerge conflicts, every deploy is risky
Fan-in / fan-outHow many modules use me / how many I useemployee used by 3 packagesHigh fan-out = many reasons to change
Change couplingFiles that change together in git historyOrder.php and InvoicePdf.php in 80% of commitsHidden dependency nobody drew

The rule in three sentences.

Martin's wordingWhat it means in practice
"one and only one reason to change" (2014)Count the actors, not the methods
"Gather together the things that change for the same reasons" (2014)Cohesion: what one actor changes lives together
"Separate those things that change for different reasons" (2014)Coupling: different actors never share a file they both edit

Where SRP lives in your tools.

LevelGoLaravel
FunctionOne job per function, small signaturesOne job per method
Type / classA type with methods for one actorForm Request, Action, Policy, Job, Listener, Observer
Package / moduleA package is the unit of change; internal/ hides helpersA module folder or Composer package with its own service provider
DeployableOne binary per cmd/<name>One app, or one service per bounded context
TeamCODEOWNERS per package pathCODEOWNERS per module path

Why SRP exists ​

Software changes because people ask it to. When one module serves several groups of people, a change requested by one group can break what another group relies on, and the second group did not ask for anything. Martin's 2014 post describes exactly this: the operations team's report breaks because someone changed the finance team's pay calculation. SRP is the rule that prevents it: put the code each group changes in its own module, so the blast radius of a request is that group's code only.

One big moduleMany focused modules
Easy to find "where everything is" at firstEasy to find "where this actor's rules are"
One change can break unrelated featuresA change stays inside one actor's module
Merge conflicts between teamsTeams edit different files
Tests need the whole world (database, mailer, PDF)Pure rules are tested without I/O
Few files, few names to inventMore files, more names, more navigation
Risk: god classRisk: over-splitting, shotgun surgery
FinanceAuditPlatformtype Employee (before)CalculatePay()ReportHours()Save(db)shared regularHours()3 actors, 1 type, 5 imports:a pay change silently moves the audit reportFinanceAuditPlatformpayrollown thresholdhoursreportown ruleemployeestoreSQL, driveremployeeplain data, fan-in 31 actor per package: a pay change touches 1 file

The picture is the kata from the lab: on the left, three actors send change requests into one Employee type that shares a regularHours helper; on the right, each actor owns a package and all three depend on a plain employee data package.

The analogy we reuse on this page: a small restaurant. One person is chef, cashier and waiter. It works until the health inspector changes kitchen rules, the tax office changes receipts and customers want table service in another language. Now three authorities who never talk to each other pull one person in three directions, and a new receipt format makes the soup late. Hiring a cashier does not make the chef less important; it means the tax office never interrupts dinner again.

Three common misunderstandings, up front ​

  1. "SRP means a class should do one thing." That is a different, older rule about functions. A payroll module does many things; it still has one reason to change if only finance changes it.
  2. "SRP means small classes." Size is a symptom, not the rule. Ten methods that one actor changes together are fine; two methods that two actors change are not.
  3. "Duplicated code must always be merged." Only if both copies change for the same reason. Two copies that serve two actors are accidental duplication, and merging them creates the coupling SRP is trying to remove.

Where it comes from ​

Parnas, 1972. David Parnas's On the Criteria To Be Used in Decomposing Systems into Modules (Communications of the ACM, December 1972) compared two ways to split the same program. The conventional split followed the steps of a flowchart. His proposed split put each design decision that is likely to change inside one module:

"Every module in the second decomposition is characterized by its knowledge of a design decision which it hides from all others." — D. L. Parnas, On the Criteria To Be Used in Decomposing Systems into Modules, CACM 15(12), 1972

That is information hiding, and it is the root of SRP: you split by what will change, not by the order things happen in.

Stevens, Myers and Constantine, 1974. The Structured Design paper in the IBM Systems Journal gave us the two words every SRP argument still uses. It defines coupling as "the measure of the strength of association established by a connection from one module to another", calls cohesion binding, and ranks it from weakest to strongest: coincidental, logical, temporal, communicational, sequential, functional. Later textbooks (Yourdon and Constantine's 1979 book onwards, as summarised on Wikipedia) add procedural cohesion to make seven levels.

DeMarco and Page-Jones, late 1970s and 1980s. Martin's own SRP chapter credits them: "This principle was described in the work of Tom DeMarco and Meilir Page-Jones. They called it cohesion."

Martin, 2000. His paper Design Principles and Design Patterns has no SRP. The nearest thing is a package principle, the Common Closure Principle: "Classes that change together, belong together."

Martin, 2002. The SRP chapter of Agile Software Development: Principles, Patterns, and Practices (we read the draft Object Mentor published as a PDF, where it is numbered Chapter 9) states the rule for classes:

"THERE SHOULD NEVER BE MORE THAN ONE REASON FOR A CLASS TO CHANGE." — Robert C. Martin, SRP: The Single Responsibility Principle (chapter draft, Object Mentor)

It defines a responsibility as "a reason for change" and uses two examples: a Rectangle with both area() and draw() that drags GUI code into a geometry application, and a Modem interface whose dial/hangup and send/recv change for different reasons.

Martin, 2014. The blog post moves the definition from code to people. The question is not "what does this class do" but "who must the design of the program respond to?":

"This principle is about people." — Robert C. Martin, The Single Responsibility Principle, 2014

and gives the version to memorise:

"Gather together the things that change for the same reasons. Separate those things that change for different reasons." — Robert C. Martin, The Single Responsibility Principle, 2014

In the same post he links it to the older words: "this is just another way to define cohesion and coupling." In his 2017 book Clean Architecture (not quoted here; we did not read the text) he rephrases the module as being responsible to one actor, a group of users or stakeholders who want the same change. The 2014 post already says the same thing in other words: "a single tightly coupled group of people representing a single narrowly defined business function."

Dissent, 2021. Dan North's CUPID: the back story calls SRP the "Pointlessly Vague Principle" because "What is one thing anyway?" The answer this page gives is Martin's 2014 one: "one thing" is the wrong reading; "one actor" is the right one. North's replacement property, "Unix philosophy: does one thing well", is about how code is used; SRP is about how it changes. Both are useful.

The concepts, one by one ​

Each block follows the same order: plain words, the usual wrong belief, a precise definition, a change-request timeline, real scenarios, how languages express it, and the fix.

Reason to change Must-know ​

In plain words: a reason to change is somebody who will ask you to change this code. Count them.

Common misunderstanding: "A bug fix or a refactoring is a reason to change." Martin answers this directly in 2014: bug fixes and refactorings are the programmer's responsibility, not the program's. The reasons that count come from the business: rules, formats, regulations, infrastructure choices.

Definition: a reason to change is an independent source of requirements whose changes arrive on their own schedule. A module has one responsibility when every expected change to it originates from the same source.

text
     Week   Request (who asks)                    Files touched (god class)   Files touched (SRP)
1    W1     Overtime after 7h, not 8h (finance)   employee.go                 payroll/payroll.go
2    W1     -- audit report now shows 7h days, nobody asked for that --
3    W2     Report must include weekends (audit)  employee.go                 hoursreport/hoursreport.go
4    W3     Move from MySQL to PostgreSQL (platf.) employee.go                employeestore/store.go
5           three actors, one file, three re-tests  vs  three actors, three files, one re-test each

Real scenario: an e-commerce Order class that prices (finance), persists (platform), renders the invoice (marketing) and validates the API payload (API owners); a User model that holds authentication, billing, notification preferences and GDPR export; a Go server package that contains HTTP routing, SQL, and the business rules.

Fix: list the actors for each module (a two-column table: module → who files the tickets). Any row with more than one actor is a candidate for Extract Class.

Actor and stakeholder Must-know ​

In plain words: an actor is one group of people who want the same things from the code: the payroll team, the auditors, the platform team. A stakeholder is a single person in such a group.

Common misunderstanding: "Actor means user role, like admin or customer." Not here. Two user roles can be one actor (both use the same report, owned by one team), and one role can involve several actors (a customer's checkout touches pricing, fraud and fulfilment, each owned by someone else).

Definition: an actor is the set of stakeholders whose change requests are correlated: they want the same module to change for the same reasons at the same time. SRP asks that a module answer to one actor.

text
     Actor            Owns which rule                         Lives in
1    Finance (CFO)    pay, overtime, tax                      payroll
2    Audit (COO)      what the hours report shows             hoursreport
3    Platform (CTO)   schema, database engine, SQL            employeestore
4    All three        what an Employee *is* (id, name, rate)  employee  (stable, rarely changes)

Real scenario: a Laravel monolith where marketing changes the invoice PDF weekly, finance changes VAT twice a year, and the API team changes validation for each mobile release. A Go service where the SRE team changes metrics and logging while the product team changes the business flow.

Fix: write the actors into CODEOWNERS (GitHub, GitLab) by path, so the tooling enforces the boundary: a pull request that touches two owners' paths needs two approvals, which is SRP made visible.

Cohesion Must-know ​

In plain words: cohesion is how much the parts of a module belong together. High cohesion: everything in payroll is about pay. Low cohesion: utils holds a date formatter, a retry helper and a tax rate.

Common misunderstanding: "If all methods use the same fields, the class is cohesive." Field sharing is one signal (it is what LCOM measures), but a class can share one big field, a database connection, between unrelated methods and still serve three actors.

Definition: Stevens, Myers and Constantine called it binding, "the measure of the cohesiveness of a module", and ranked it:

Level (1974 name)In plain wordsExampleVerdict
CoincidentalGrouped by accidenthelpers.php, package utilsWorst
LogicalSame category, different jobsExporter with CSV, PDF and XML branches picked by a flagWeak
TemporalRuns at the same timebootstrap() that opens the DB, warms cache and sends a pingWeak
Procedural (later texts)Steps of one procedure"check permission then open file"Medium
CommunicationalWorks on the same dataMethods that all read the same OrderGood
SequentialOutput of one is input of the nextparse → validate → normalise pipelineGood
FunctionalEverything contributes to one taskpayroll.CalculatePay and its helpersBest
text
     Request                         Low-cohesion utils package        Cohesive packages
1    change date format for audit    edit utils/strings.go             edit hoursreport
2    -- payroll imports utils too, so payroll is rebuilt, retested, redeployed --
3    change retry policy for HTTP    edit utils/retry.go               edit httpclient

Fix: move each function in utils next to its only caller, or into a package named after what it does (money, retry, slug). Cheney's rule for Go: a package name must describe its purpose, so common, utils, helpers, misc, base are warnings.

Coupling Must-know ​

In plain words: coupling is how much changing one module forces changes in another.

Common misunderstanding: "Coupling is bad; remove it." Fowler's Reducing Coupling (IEEE Software, 2001) says the opposite: modules must communicate, and "if you ban coupling between modules, you have to put everything in one big module." The goal is to control it: few, stable, one-directional dependencies.

Definition: Fowler's working test: "If changing one module in a program requires changing another module, then coupling exists." Forms, from loosest to tightest:

FormWhat is sharedExampleHow bad
Data couplingSimple parametersCalculatePay(e Employee) int64Fine
Stamp couplingA whole structure, partly usedPassing an Eloquent model when only id is neededMild
Control couplingA flag that picks behaviourrender($order, isPdf: true)Smell: two jobs
External couplingA format or protocolTwo services parse the same CSVNeeds a contract
Common couplingGlobal or shared mutable dataPackage-level var DB *sql.DB, config() everywhereHidden, wide
Content couplingReaching into internalsReflection on private fields, raw SQL into another module's tablesWorst
Change (logical) couplingNothing in code; they just change togetherOrder.php and invoice.blade.php in the same commitsInvisible without git analysis
DuplicationCopy-pasted logicTwo VAT calculationsFowler: "Duplication always implies coupling"

Cohesion and coupling are two axes of one picture (the full treatment is the chapter Design Quality). The goal is the top-right corner; the arrows are the refactoring moves from Mechanics.

Shotgun surgeryeach part cohesive, but one changeedits many modules or services(distributed monolith)SRP goalone actor, one module,few, stable dependenciesGod classmany actors, high LCOM, high CBOevery change risks every featureutils / commoncoincidental cohesiongrows without reasonExtract ClassMove Method / mergeMove Functioncoupling: high (left) to low (right)cohesion: high (top) to low (bottom)

Fix: depend on data, not on behaviour flags; pass the smallest type that works; put shared mutable state behind one owner; make change coupling visible with the git query below.

Accidental duplication Important ​

In plain words: two pieces of code look identical today but belong to different actors, so they will diverge tomorrow. They are not real duplicates.

Common misunderstanding: "DRY says merge them." DRY is about knowledge: one rule in one place. Two rules that happen to have the same formula are two pieces of knowledge.

Definition: duplication is true when both copies must always change together (the same actor, the same rule). It is accidental when the copies have different reasons to change. Merging accidental duplication couples two actors through a shared helper.

text
     Day   Event
1    D1    payroll and hoursreport both need "regular hours = min(hours, 8)"
2    D1    a developer extracts regularHours() into Employee; looks clean
3    D30   finance: "regular hours stop at 7 for night shifts"
4    D30   developer edits regularHours(); payroll tests pass
5    D31   auditors find the hours report changed; nobody asked them; compliance incident

Real scenario: the "regular hours" helper above (this is the kata in the lab); a formatMoney() used by invoices (legal format, finance) and by marketing banners (rounded, marketing); one validation rule set shared by the public API and the admin panel; one UserResource used by the mobile app and by a partner export.

Fix: keep the copies, each in its owner's module, with a comment that says why. Merge only when you can name one actor who owns the rule.

SRP is not "do one thing" Important ​

In plain words: "a function should do one thing" is a rule about functions and readability. SRP is a rule about modules and people.

Common misunderstanding: "SRP: every class has one public method." That produces dozens of one-method classes that one actor must edit together for every change: high coupling, the opposite of the goal.

Definition: "Do one thing" (often attributed to Martin's Clean Code for functions) concerns levels of abstraction inside a function. SRP concerns the set of actors a module answers to. A module can contain many functions that each do one thing and still have one reason to change.

RuleScopeQuestionFailure mode
Do one thingFunctionIs every line at one level of abstraction?Long functions mixing SQL and rules
SRPClass, package, serviceHow many actors change this?God class, or over-split shotgun surgery
Unix "does one thing well" (CUPID)Program, componentIs it easy to use and compose?Tools that do everything badly

God class Must-know ​

In plain words: one class that knows and does too much, so every feature passes through it and every actor edits it.

Common misunderstanding: "It is just a big class; size is fine." Size alone is fine. The problem is that a god class has high fan-in (everyone uses it) and many actors (everyone edits it): every change is risky and every merge conflicts.

Definition: a class with many unrelated responsibilities, low cohesion (high LCOM), high coupling (high CBO and fan-out), and high churn in git history. In Laravel the typical god classes are the User model and a Helper/Service class; in Go, a Server struct with 40 methods.

text
     Sprint   Team            Change to User.php                 Result
1    S1       Billing         add stripe_customer_id logic      merge conflict with Auth team
2    S1       Auth            add 2FA columns and methods        conflict resolved by hand
3    S2       Marketing       add newsletter preferences         accidentally removes a cast
4    S2       Billing         invoices stop working; root cause is a marketing commit

Fix: Extract Class by actor (BillingProfile, TwoFactorSettings, NewsletterPreferences as separate models or value objects), move behaviour to Actions/Policies/Observers, and keep the model as data plus relationships. See god model.

Fan-in and fan-out Good to know ​

In plain words: fan-in is how many modules depend on me; fan-out is how many modules I depend on.

Common misunderstanding: "High fan-in is bad." High fan-in on a stable, small module (employee, money, time) is good: it is reused. High fan-in on a module that changes often is the danger: every change ripples to all callers.

Definition: the CK metrics tool defines FAN-IN as "the number of input dependencies a class has" and FAN-OUT as "the number of output dependencies". High fan-out means many reasons to change arrive from below; high fan-in means many modules feel each change.

ModuleFan-inFan-outChange rateVerdict
employee (data)31 (time)RareHealthy core
payroll11MonthlyHealthy
God Employee (before)3 actors5 importsWeeklyUnhealthy: high both
utils4012WeeklyWorst: coincidental + hub

Package as the unit of change (Go) Important ​

In plain words: in Go, the package, not the type, is where responsibility is drawn, because the package is what you import, version, test and review.

Common misunderstanding: "Go has no classes, so SRP does not apply." Cheney's 2016 talk maps it directly: "each Go package is itself a small Go program, a single unit of change, with a single responsibility."

Definition: a Go package has one name, one import path and one exported API. Its name should describe its purpose; import creates source-level coupling. internal/ directories limit who may import a package (the Go 1.4 release notes: "a package .../a/b/c/internal/d/e/f can be imported only by code in the directory tree rooted at .../a/b/c"). cmd/<name>/ holds one main package per binary (the official module layout guide).

text
     Change request                Go layout                               Rebuilt and retested
1    new overtime rule             payroll/payroll.go                      payroll + its importers
2    new report column             hoursreport/hoursreport.go              hoursreport only
3    swap PostgreSQL driver        employeestore/store.go, cmd/api/main.go employeestore, cmd/api
4    refactor a helper in internal/money: no external module can import it, so no external break

Fix: see the Go angle for a full layout.

Module boundaries and the facade Important ​

In plain words: a module boundary is the line around a group of code that one actor owns; a facade is the single front door through which other modules talk to it.

Common misunderstanding: "Splitting into classes is enough." If every other module can reach every class inside Billing, the internal split does not protect anything: callers couple to internals and the module cannot change.

Definition: a module exposes a narrow public API (a facade, in the Gang of Four sense: one simplified interface to a subsystem) and hides the rest (Parnas's information hiding). In Go the facade is the exported API of the top package with helpers under internal/; in Laravel it is a small set of public Action classes or a contract bound in the module's service provider. (Not to be confused with Laravel's facades, which are static proxies to container services.)

text
     Caller (Orders module)          Billing module boundary
1    $billing->chargeOrder($order)   -> Billing\ChargeOrder (public Action, the facade)
2                                       -> internal: TaxCalculator, StripeClient, InvoiceRepo
3    Orders never imports TaxCalculator; Billing can rewrite it freely

Fix: pick one entry point per use case, mark the rest internal (internal/ in Go; @internal docblock plus an architecture test in PHP), and write an architecture test that fails if another module imports an internal class.

Conway's law and team ownership Important ​

In plain words: your system ends up shaped like your org chart. If two teams share one module, the module will have two reasons to change.

Common misunderstanding: "Conway's law is a joke about bad architecture." It is a structural observation from 1968, and it is the reason SRP is "about people".

Definition: Melvin Conway, How Do Committees Invent? (Datamation, 1968):

"organizations which design systems (in the broad sense used here) are constrained to produce designs which are copies of the communication structures of these organizations." — Melvin E. Conway, How Do Committees Invent?, 1968

The Inverse Conway Maneuver (a term Fowler's bliki page credits to Jonny LeRoy and Matt Simons, 2010) is the deliberate use of it: shape teams the way you want the architecture to look. SRP and Conway's law meet at team ownership: each module has one owning team, and the module's boundary follows the team's responsibility.

Real scenario: a payments service changed by three teams needs release coordination on every deploy; splitting it by team (checkout, payouts, reconciliation) removes the meetings. A Laravel monolith where app/Models is edited by every team becomes app/Modules/{Billing,Catalog,Shipping} with CODEOWNERS per folder.

Per-language and per-framework view ​

Language / frameworkNatural unit of changeWhere SRP homes come fromBoundary enforcementMetrics tooling
GoPackagePackage per purpose, internal/, cmd/<binary>Compiler: internal/ import rule; unexported identifiersgo list -deps, import graph; change coupling from git
PHP / LaravelClass + module folderForm Request, Action, Policy, Job, Listener, Observer, Mailable, Notification, CastNamespaces; architecture tests (Pest arch() or deptrac-style rules)Static analysers report coupling; git change coupling
Java / SpringClass + package + Maven/Gradle module@Service, @Repository, @Controller stereotypesPackage-private visibility; Java modules (module-info.java)CK tool (CBO, LCOM, FAN-IN, FAN-OUT)
C# / .NETClass + assembly (project)Controllers, services, MediatR-style handlers, IOptions<T>internal visibility per assembly; project referencesVisual Studio Code Metrics ("Class Coupling")
TypeScriptES module (file) + packageOne module per concern; barrel files as facadesexports map in package.json; lint import rulesDependency graph tools; git change coupling
PythonModule + packageOne module per concern; __all__ as public APILeading underscore convention; import lintersImport graph; git change coupling

Java's CK tool, read on its README, defines the class-level metrics this page uses: CBO "Counts the number of dependencies a class has", LCOM "Lack of Cohesion of Methods" (with the note that the first version "is not reliable"), and FAN-IN/FAN-OUT. Visual Studio's code metrics page defines Class Coupling as coupling "to unique classes through parameters, local variables, return types, method calls, generic or template instantiations, base classes, interface implementations, fields defined on external types, and attribute decoration".

The storage adapter is the classic place where a responsibility is not the business's: whether employeestore talks to PostgreSQL, MySQL with InnoDB, SQL Server or Oracle, and whether a cache in Redis or a document store such as MongoDB sits beside it, is the platform team's reason to change, and payroll must not notice.

Mechanics ​

Finding the actors: the responsibility table Must-know ​

Before refactoring, write this table for the module. It takes ten minutes and replaces opinions with facts.

Method / fileWho asks for changesLast 3 change ticketsSame actor as row 1?
CalculatePayFinanceovertime, bonus, tax yearyes
ReportHoursAudit / operationsweekend column, CSV export, fontno
SavePlatformPostgreSQL 17 upgrade, index, driverno

Three "no"s in one module means three responsibilities.

Metrics: LCOM, CBO and their limits Important ​

MetricWhat it countsHigh value meansLimit
LCOM (Lack of Cohesion of Methods)Pairs of methods that share no fields vs pairs that doMethods form separate clusters: candidate for Extract ClassSeveral variants (LCOM, LCOM*, LCOM-HS); CK warns the first is unreliable; blind to actors
CBO (Coupling Between Objects)Number of other classes this class depends onMany reasons to change arrive from outsideCounts dependencies on stable types (e.g. time.Time) too
FAN-INClasses that reference this oneMany modules feel each changeGood if the module is stable
FAN-OUTClasses this one referencesDepends on many detailsNormal for composition roots (main, providers)
Change coupling (logical coupling)How often two files change in the same commitHidden dependency or split responsibilityNeeds history; large refactoring commits add noise
ChurnLines changed per file per periodHotspotHigh churn + high complexity = top refactoring target

LCOM and CBO come from code; they find structural clusters. Only change coupling comes from history, so only it sees actors indirectly: files that one actor's tickets keep touching together.

Change coupling from git history Must-know ​

Adam Tornhill's code-maat README defines the idea: "Logical coupling refers to modules that tend to change together." You can compute it with code-maat (-a coupling, with --min-coupling defaulting to 30 percent) or with a few lines of shell and SQLite:

bash
# one row per (commit, file) for the last year
git log --since=1.year --name-only --pretty=format:'@%H' \
 | awk '/^@/{c=substr($0,2);next} NF{print c","$0}' > changes.csv
sqlite3 coupling.db '.mode csv' 'CREATE TABLE changes(sha TEXT, file TEXT);' '.import changes.csv changes'
sql
-- pairs of files that change together, with a coupling degree in percent
WITH revs AS (
  SELECT file, COUNT(DISTINCT sha) AS n FROM changes GROUP BY file
), pairs AS (
  SELECT a.file AS f1, b.file AS f2, COUNT(DISTINCT a.sha) AS shared
  FROM changes a JOIN changes b ON a.sha = b.sha AND a.file < b.file
  GROUP BY a.file, b.file
)
SELECT p.f1, p.f2, p.shared,
       ROUND(100.0 * p.shared / ((r1.n + r2.n) / 2.0)) AS degree
FROM pairs p
JOIN revs r1 ON r1.file = p.f1
JOIN revs r2 ON r2.file = p.f2
WHERE p.shared >= 5
ORDER BY degree DESC
LIMIT 20;
-- app/Models/Order.php | resources/views/invoices/show.blade.php | 41 | 78

Read the result two ways. A high degree across different actors' folders means an SRP violation that the folder structure hides. A high degree between files in one module is normal cohesion. A high degree between two services means a distributed monolith.

Refactoring moves Must-know ​

The names are from Fowler's Refactoring catalogue.

MoveWhenMechanics in one lineGoLaravel
Extract ClassOne class, two actorsCreate the new class, move fields, then methods, one at a time, tests green after eachNew type or new packageNew Action / value object / model
Move Method (Move Function)A method uses another class's data more than its ownCopy to the target, delegate from the old place, then inline the delegateMove func to the package that owns the dataMove logic from controller to Action/Policy
Move FieldA field belongs to another actor's conceptAdd to target, redirect reads/writes, removeMove struct fieldMove column to its own table/model
Extract FunctionLong method mixing levelsName the step, pass what it needsSmall unexported funcsPrivate methods or invokable class
Split PhaseCode does "parse then compute then format"Introduce an intermediate data structure between phasesParse → struct → compute → renderForm Request → DTO → Action → Resource
Introduce Facade / Hide DelegateCallers reach into internalsOne public entry point; move the rest to internalinternal/Public Action + @internal
Inline Class (the reverse)Over-split: two classes always change togetherMove everything into one and delete the otherMerge packagesMerge Actions

Go ​

Before ​

One Order type prices itself, saves itself to PostgreSQL and renders its own HTML invoice. Finance, the platform team and marketing all have a key to the same room.

go
package before

import (
	"database/sql"
	"fmt"
	"strings"
)

type Line struct {
	SKU      string
	Qty      int
	UnitCent int64
}

// Order knows how to price itself, persist itself, and render itself.
// Three different people will ask for changes here:
// finance (pricing rules), the platform team (storage), and marketing (invoice layout).
type Order struct {
	ID    string
	Lines []Line
}

func (o *Order) TotalCents() int64 {
	var sum int64
	for _, l := range o.Lines {
		sum += int64(l.Qty) * l.UnitCent
	}
	return sum
}

func (o *Order) Save(db *sql.DB) error {
	_, err := db.Exec(`INSERT INTO orders (id, total) VALUES ($1, $2)`, o.ID, o.TotalCents())
	return err
}

func (o *Order) RenderInvoiceHTML() string {
	var b strings.Builder
	fmt.Fprintf(&b, "<h1>Invoice %s</h1><ul>", o.ID)
	for _, l := range o.Lines {
		fmt.Fprintf(&b, "<li>%s × %d</li>", l.SKU, l.Qty)
	}
	fmt.Fprintf(&b, "</ul><p>Total: %d</p>", o.TotalCents())
	return b.String()
}

After ​

Three types, three owners. Order is now pure business logic. The repository can switch databases without finance noticing. The renderer writes to an io.Writer, so the same invoice can go to an HTTP response, a file or a test buffer.

go
package after

import (
	"context"
	"database/sql"
	"fmt"
	"io"
)

type Line struct {
	SKU      string
	Qty      int
	UnitCent int64
}

// Order is now only about the business rule: what does this order cost?
// Only finance has a reason to change it.
type Order struct {
	ID    string
	Lines []Line
}

func (o Order) TotalCents() int64 {
	var sum int64
	for _, l := range o.Lines {
		sum += int64(l.Qty) * l.UnitCent
	}
	return sum
}

// OrderRepository answers to the platform team: how and where orders are stored.
type OrderRepository struct{ DB *sql.DB }

func (r OrderRepository) Save(ctx context.Context, o Order) error {
	_, err := r.DB.ExecContext(ctx,
		`INSERT INTO orders (id, total) VALUES ($1, $2)`, o.ID, o.TotalCents())
	return err
}

// InvoiceRenderer answers to marketing: how an invoice looks.
type InvoiceRenderer struct{}

func (InvoiceRenderer) WriteHTML(w io.Writer, o Order) error {
	if _, err := fmt.Fprintf(w, "<h1>Invoice %s</h1><ul>", o.ID); err != nil {
		return err
	}
	for _, l := range o.Lines {
		if _, err := fmt.Fprintf(w, "<li>%s × %d</li>", l.SKU, l.Qty); err != nil {
			return err
		}
	}
	_, err := fmt.Fprintf(w, "</ul><p>Total: %d</p>", o.TotalCents())
	return err
}

The Go angle ​

Cheney's talk puts the unit of responsibility at the package: a package's name "is both a description of its purpose, and a name space prefix", and catch-all packages "become a dumping ground for miscellany, and because they have many responsibilities they change frequently and without cause." The standard library shows the shape: net/http knows nothing about JSON and encoding/json knows nothing about sockets.

A service laid out by actor and by the official module layout guide:

text
shop/
  cmd/
    api/main.go          # composition root for the HTTP binary
    worker/main.go       # composition root for the queue consumer
  internal/
    pricing/             # finance: rules only, no I/O
    invoice/             # marketing: rendering
    orderstore/          # platform: SQL, driver, migrations
    httpapi/             # API team: routing, decoding, status codes
  go.mod

Two Go rules make this hold. First, internal/ is enforced by the go command, so other modules cannot couple to your helpers. Second, Go forbids import cycles, so if pricing imports orderstore and orderstore imports pricing, the build fails and you are forced to find the real owner of the shared concept.

go
// cmd/api/main.go: the only file that knows every concrete piece.
func main() {
	db, err := sql.Open("pgx", os.Getenv("DATABASE_URL"))
	if err != nil {
		log.Fatal(err)
	}
	store := orderstore.New(db)
	h := httpapi.New(store, pricing.Default(), invoice.HTML{})
	log.Fatal(http.ListenAndServe(":8080", h))
}

Laravel ​

Before ​

A single invokable controller validates, prices, persists, renders a PDF and sends an email. Four stakeholders, one file, and every change risks every other feature.

php
<?php

namespace App\Http\Controllers;

use App\Models\Order;
use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;

// One controller, four masters: the product owner (validation rules),
// finance (pricing), the DBA (how rows are written), and marketing (the PDF and the email).
class PlaceOrderController extends Controller
{
    public function __invoke(Request $request)
    {
        $data = $request->validate([
            'lines' => ['required', 'array', 'min:1'],
            'lines.*.sku' => ['required', 'string'],
            'lines.*.qty' => ['required', 'integer', 'min:1'],
        ]);

        $total = 0;
        foreach ($data['lines'] as $line) {
            $price = DB::table('products')->where('sku', $line['sku'])->value('price_cents');
            $total += $price * $line['qty'];
        }
        if ($request->user()->is_vip) {
            $total = (int) round($total * 0.8);
        }

        $order = DB::transaction(function () use ($request, $data, $total) {
            $order = Order::create(['user_id' => $request->user()->id, 'total_cents' => $total]);
            foreach ($data['lines'] as $line) {
                $order->lines()->create($line);
            }

            return $order;
        });

        $pdf = Pdf::loadView('invoices.show', ['order' => $order]);
        Mail::raw('Thanks for your order', function ($m) use ($request, $pdf) {
            $m->to($request->user()->email)->attachData($pdf->output(), 'invoice.pdf');
        });

        return response()->json($order, 201);
    }
}

After ​

Laravel already gives each concern a home. The form request owns validation. A small pricing class owns the business rule and can be unit-tested without a database. An action class owns the use case. The invoice email is an event listener, so marketing can redesign it without touching pricing. The controller translates HTTP into a call.

php
<?php

// app/Http/Requests/PlaceOrderRequest.php — owned by whoever owns the API contract.
namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class PlaceOrderRequest extends FormRequest
{
    public function rules(): array
    {
        return [
            'lines' => ['required', 'array', 'min:1'],
            'lines.*.sku' => ['required', 'string'],
            'lines.*.qty' => ['required', 'integer', 'min:1'],
        ];
    }
}

// app/Pricing/OrderPricer.php — owned by finance. No I/O, trivially unit-tested.
namespace App\Pricing;

use App\Models\User;

final class OrderPricer
{
    /** @param array<int, array{sku: string, qty: int, price_cents: int}> $lines */
    public function total(array $lines, User $buyer): int
    {
        $total = array_sum(array_map(fn ($l) => $l['price_cents'] * $l['qty'], $lines));

        return $buyer->is_vip ? (int) round($total * 0.8) : $total;
    }
}

// app/Actions/PlaceOrder.php — the use case. It coordinates; it does not know HTTP, PDF, or SMTP.
namespace App\Actions;

use App\Events\OrderPlaced;
use App\Models\Order;
use App\Models\Product;
use App\Models\User;
use App\Pricing\OrderPricer;
use Illuminate\Support\Facades\DB;

final class PlaceOrder
{
    public function __construct(private OrderPricer $pricer) {}

    /** @param array<int, array{sku: string, qty: int}> $lines */
    public function handle(User $buyer, array $lines): Order
    {
        $prices = Product::whereIn('sku', array_column($lines, 'sku'))->pluck('price_cents', 'sku');
        $priced = array_map(fn ($l) => $l + ['price_cents' => $prices[$l['sku']]], $lines);

        $order = DB::transaction(function () use ($buyer, $priced) {
            $order = Order::create([
                'user_id' => $buyer->id,
                'total_cents' => $this->pricer->total($priced, $buyer),
            ]);
            $order->lines()->createMany($priced);

            return $order;
        });

        OrderPlaced::dispatch($order);

        return $order;
    }
}

// app/Listeners/SendInvoice.php — owned by marketing. Changing the PDF never touches pricing.
namespace App\Listeners;

use App\Events\OrderPlaced;
use App\Mail\InvoiceMail;
use Illuminate\Support\Facades\Mail;

final class SendInvoice
{
    public function handle(OrderPlaced $event): void
    {
        Mail::to($event->order->user)->send(new InvoiceMail($event->order));
    }
}

// app/Http/Controllers/PlaceOrderController.php — now it only translates HTTP.
namespace App\Http\Controllers;

use App\Actions\PlaceOrder;
use App\Http\Requests\PlaceOrderRequest;

class PlaceOrderController extends Controller
{
    public function __invoke(PlaceOrderRequest $request, PlaceOrder $placeOrder)
    {
        $order = $placeOrder->handle($request->user(), $request->validated('lines'));

        return response()->json($order, 201);
    }
}

The Laravel angle ​

The framework's vocabulary is a list of responsibilities, each with a generator command and a documented slot:

Laravel classResponsibilityGeneratorOwner (typical actor)
Form RequestValidation and request authorization: Laravel's docs say it has two methods, authorize and rulesmake:requestAPI contract owner
Action (convention, not a framework class)One use case, transaction boundary(plain class)Product / domain team
PolicyWho may do what to a modelmake:policySecurity / product
JobWork done later, retried, on a queuemake:jobPlatform + domain
ListenerReaction to an eventmake:listenerThe team that owns the reaction
ObserverReactions to Eloquent model events, grouped in one classmake:observerData owner
Mailable / NotificationMessage content and channelmake:mail, make:notificationMarketing / comms
ResourceJSON shape of a modelmake:resourceAPI contract owner
php
// app/Policies/OrderPolicy.php: the security rule, nowhere else.
final class OrderPolicy
{
    public function refund(User $user, Order $order): bool
    {
        return $user->is_admin || ($order->user_id === $user->id && $order->created_at->gt(now()->subDays(14)));
    }
}

// app/Jobs/GenerateInvoicePdf.php: slow work, retried, off the request path.
final class GenerateInvoicePdf implements ShouldQueue
{
    use Queueable;

    public function __construct(public Order $order) {}

    public function handle(InvoiceRenderer $renderer): void
    {
        Storage::put("invoices/{$this->order->id}.pdf", $renderer->pdf($this->order));
    }
}

// app/Observers/OrderObserver.php: data-lifecycle reactions, registered with #[ObservedBy].
final class OrderObserver
{
    public function created(Order $order): void
    {
        GenerateInvoicePdf::dispatch($order)->afterCommit();
    }
}

The #[ObservedBy([OrderObserver::class])] attribute on the model registers the observer (Laravel 13 Eloquent docs). A fat controller or a thousand-line Eloquent model is almost always SRP being ignored despite the framework offering the separation for free.

Solving the classic problems ​

ProblemSolutionHowAdvantageCost / limitation
Fat controllerSplit by Laravel slotForm Request + Action + Resource + ListenerEach slot tested aloneMore files to navigate
God modelExtract Class by actorValue objects, related models, Policies, ObserversFewer conflictsMigration for moved columns
utils / common packageMove Function to callersOne package per purposePackages with names that mean somethingSome tiny packages
Shared helper across actorsKeep accidental duplicationCopy into each owner, comment whyActors decoupledTwo copies to read
Service changed by 3 teamsSplit by team or make a modular monolithModule per team + CODEOWNERSIndependent deploysCross-module calls need contracts
Over-split (shotgun surgery)Inline ClassMerge classes that always change togetherOne change, one fileLarger class

Fat controller ​

Use the Laravel snippet above: validation moves to PlaceOrderRequest, pricing to OrderPricer, the use case to PlaceOrder, the email to a listener. Measured on the snippets: the controller's use imports drop from 5 to 2, and a change to the PDF touches only the listener.

God model ​

php
// Before: User.php has 60 methods for auth, billing, newsletter and export.
// After: the model keeps data and relationships; each actor gets a home.
final class User extends Authenticatable
{
    public function billingProfile(): HasOne { return $this->hasOne(BillingProfile::class); }
    public function newsletter(): HasOne { return $this->hasOne(NewsletterPreference::class); }
}

final class ExportUserData // GDPR export: legal team's actor
{
    public function handle(User $user): array
    {
        return ['user' => $user->only('id', 'email', 'created_at'), 'orders' => $user->orders()->get()->toArray()];
    }
}
sql
-- Move Field at the database level: billing columns leave the users table.
CREATE TABLE billing_profiles (
  user_id     BIGINT PRIMARY KEY REFERENCES users(id),
  stripe_id   TEXT,
  vat_number  TEXT
);
INSERT INTO billing_profiles (user_id, stripe_id, vat_number)
SELECT id, stripe_id, vat_number FROM users WHERE stripe_id IS NOT NULL;
-- drop the old columns in a later release (expand/contract)

Shared helper across actors ​

The fix is counter-intuitive: duplicate on purpose. The kata after has payroll.regularHours and hoursreport.Write each computing regular hours with their own constant.

Choosing: split or merge ​

SituationRecommendationExtra techniqueReason
Two actors edit one classSplit (Extract Class)CODEOWNERS per fileDifferent reasons to change
Two classes always change in the same commitMerge (Inline Class)Check change coupling firstOne reason to change, split by accident
Code looks duplicated, different ownersKeep both copiesComment the ownerAccidental duplication
Code duplicated, same owner, same ruleMergeExtract FunctionTrue duplication
Package named utils / commonDissolveMove Function to callersCoincidental cohesion
One team, small appKeep a simple structureFolders by featureSRP is about actors; one actor needs little splitting
Many teams, one repositoryModular monolithModule facades, architecture testsOwnership without network calls
Teams need independent deploysSeparate servicesContracts, events, outboxSRP plus a network boundary
Performance-critical inner loopKeep data and logic togetherMeasure firstSplitting can cost indirection (see Muratori's critique on SOLID)

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

SRP scales because "who asks for changes here?" is the same question at every size: function, class, package, module, service, team.

Monolith: one process, one database ​

How it shows up: classes and folders. The SRP failures are the god model, the fat controller and the Helpers.php file.

Simplest correct usage: use the framework's slots (Form Request, Action, Policy, Job, Listener, Observer), keep business rules free of I/O, and keep one composition root (cmd/<name>/main.go, Laravel service providers).

Example (simple): a blog: PostController → StorePostRequest → PublishPost action → PostPublished event → NotifySubscribers listener.

Example (complex): a shop where finance, marketing and fulfilment all touch Order. Split by actor into Pricing, Invoicing and Fulfilment classes with an Order model that holds data only; enforce it with CODEOWNERS.

Modular monolith and multiple databases ​

How it shows up: each module (one actor, one team) owns its code and its tables. SRP at the data level means one writer per table.

sql
-- PostgreSQL: one schema per module, one role per module.
CREATE SCHEMA billing;  CREATE SCHEMA catalog;
CREATE ROLE billing_app LOGIN;  CREATE ROLE catalog_app LOGIN;
GRANT USAGE, CREATE ON SCHEMA billing TO billing_app;
GRANT USAGE ON SCHEMA catalog TO billing_app;            -- read only
GRANT SELECT ON ALL TABLES IN SCHEMA catalog TO billing_app;
-- billing_app cannot write catalog.products: only the catalog module can.

Rules: modules talk through a facade (a public Action or interface), never through another module's tables or internal classes; a module's service provider is its only wiring; architecture tests fail the build when a module imports another's internals.

Microservices: SRP with a network boundary ​

What survives: "one actor per module" becomes "one team per service", aligned to a business capability or bounded context. What breaks: if a service is split by technical layer (an "orders-db service", an "orders-api service") instead of by actor, every feature touches several services: shotgun surgery over the network, the distributed monolith.

text
     Change request: "add gift wrapping"
1    Split by actor:    Checkout team edits checkout-svc (price +5), deploys alone
2                       Fulfilment team reacts to OrderPlaced.giftWrap in fulfilment-svc, deploys alone
3    Split by layer:    edit api-gateway, orders-api, orders-db, pricing-lib; four PRs, one release train

Example: checkout publishes OrderPlaced through an outbox; invoicing and fulfilment subscribe. Each service changes for one team's reasons, and adding a subscriber does not edit checkout (that part is Open–Closed at the architecture level; see also Event-Driven Architecture).

Distributed data: replicas, caches and shared schemas ​

Where SRP breaks: shared databases. Two services writing the same table means two reasons to change one schema. A shared Redis cache whose keys are written by several services means nobody owns invalidation. A reporting replica that every team queries with ad-hoc SQL couples every team to every schema.

Countermeasures: one owner per table and per cache key prefix; publish changes as events or through CDC instead of letting others read your tables; give analytics its own read model.

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

ScaleStructureSRP practice
1× (one team, one app)Folders by feature, framework slotsActor table in your head; avoid god classes
10× (several teams, one repo)Modular monolith, schema per moduleCODEOWNERS, facades, change-coupling report each quarter
100× (many teams, many deploys)Services per business capabilityTeam = service owner; contracts, events, no shared tables

Lab: refactoring kata ​

You refactor the provided Go code from a god type to one package per actor and measure the result. Everything runs offline.

Setup.

bash
cd docs/snippets/solid/go
go vet ./srp/kata/...           # both versions compile and are vet-clean
go
// Package before is the SRP kata's starting point: one type that answers to
// three actors (finance, operations/audit, and the platform team).
package before

import (
	"context"
	"database/sql"
	"fmt"
	"strings"
	"time"
)

type Shift struct {
	Day   time.Time
	Hours float64
}

type Employee struct {
	ID         int64
	Name       string
	HourlyRate int64 // cents
	Shifts     []Shift
}

// regularHours is shared by pay and by the audit report. It looks like
// duplication was avoided; in fact two actors now own one function.
func (e *Employee) regularHours() float64 {
	var h float64
	for _, s := range e.Shifts {
		h += min(s.Hours, 8)
	}
	return h
}

// CalculatePay is specified by finance (the CFO's organisation).
func (e *Employee) CalculatePay() int64 {
	var overtime float64
	for _, s := range e.Shifts {
		if s.Hours > 8 {
			overtime += s.Hours - 8
		}
	}
	return int64(e.regularHours()*float64(e.HourlyRate) + overtime*float64(e.HourlyRate)*1.5)
}

// ReportHours is specified by operations/audit (the COO's organisation).
func (e *Employee) ReportHours() string {
	var b strings.Builder
	fmt.Fprintf(&b, "%s: %.1f regular hours\n", e.Name, e.regularHours())
	for _, s := range e.Shifts {
		fmt.Fprintf(&b, "  %s %.1f\n", s.Day.Format("2006-01-02"), s.Hours)
	}
	return b.String()
}

// Save is specified by the platform team (the CTO's organisation).
func (e *Employee) Save(ctx context.Context, db *sql.DB) error {
	_, err := db.ExecContext(ctx,
		`UPDATE employees SET name = $1, hourly_rate = $2 WHERE id = $3`,
		e.Name, e.HourlyRate, e.ID)
	return err
}

Step 1: write the actor table. Expected: CalculatePay → finance, ReportHours → audit, Save → platform, regularHours → both finance and audit.

Step 2: measure the starting point.

bash
go list -f '{{join .Imports "\n"}}' ./srp/kata/before | wc -l
# 5   (context, database/sql, fmt, strings, time)

Step 3: reproduce the bug. Finance asks for overtime after 7 hours. Change min(s.Hours, 8) to min(s.Hours, 7) in regularHours and both 8s in CalculatePay to 7. Expected: pay changes (wanted) and the audit report's regular hours change too, because ReportHours shares regularHours (not wanted). Files touched: 1; actors affected: 2.

Step 4: Extract Class by actor. Create employee (data only), then move CalculatePay to payroll, ReportHours to hoursreport (as Write(io.Writer, Employee)), Save to employeestore. Keep the regular-hours logic duplicated in payroll and hoursreport. Compare with the reference solution:

go
// Package employee holds only the data every actor agrees on.
// It imports nothing outside the standard library's time package.
package employee

import "time"

type Shift struct {
	Day   time.Time
	Hours float64
}

type Employee struct {
	ID         int64
	Name       string
	HourlyRate int64 // cents
	Shifts     []Shift
}
go
// Package payroll answers to finance. Its overtime rule may change without
// any effect on the audit report.
package payroll

import "academy/solid/srp/kata/after/employee"

// OvertimeThreshold is finance's number, not operations'.
const OvertimeThreshold = 8.0

func regularHours(e employee.Employee) float64 {
	var h float64
	for _, s := range e.Shifts {
		h += min(s.Hours, OvertimeThreshold)
	}
	return h
}

func CalculatePay(e employee.Employee) int64 {
	var overtime float64
	for _, s := range e.Shifts {
		if s.Hours > OvertimeThreshold {
			overtime += s.Hours - OvertimeThreshold
		}
	}
	rate := float64(e.HourlyRate)
	return int64(regularHours(e)*rate + overtime*rate*1.5)
}
go
// Package hoursreport answers to operations/audit. It keeps its own
// definition of "regular hours" on purpose: the two look alike today but
// change for different reasons (accidental duplication, not real duplication).
package hoursreport

import (
	"fmt"
	"io"

	"academy/solid/srp/kata/after/employee"
)

const auditDayHours = 8.0

func Write(w io.Writer, e employee.Employee) error {
	var regular float64
	for _, s := range e.Shifts {
		regular += min(s.Hours, auditDayHours)
	}
	if _, err := fmt.Fprintf(w, "%s: %.1f regular hours\n", e.Name, regular); err != nil {
		return err
	}
	for _, s := range e.Shifts {
		if _, err := fmt.Fprintf(w, "  %s %.1f\n", s.Day.Format("2006-01-02"), s.Hours); err != nil {
			return err
		}
	}
	return nil
}
go
// Package employeestore answers to the platform team: schema, driver, SQL.
package employeestore

import (
	"context"
	"database/sql"

	"academy/solid/srp/kata/after/employee"
)

type Store struct{ DB *sql.DB }

func (s Store) Save(ctx context.Context, e employee.Employee) error {
	_, err := s.DB.ExecContext(ctx,
		`UPDATE employees SET name = $1, hourly_rate = $2 WHERE id = $3`,
		e.Name, e.HourlyRate, e.ID)
	return err
}

Step 5: measure again.

bash
for p in employee payroll hoursreport employeestore; do
  printf '%-14s ' $p; go list -f '{{join .Imports " "}}' ./srp/kata/after/$p
done
# employee       time
# payroll        academy/solid/srp/kata/after/employee
# hoursreport    academy/solid/srp/kata/after/employee fmt io
# employeestore  academy/solid/srp/kata/after/employee context database/sql
MetricBeforeAfter
Actors per unit3 in one type1 per package
Imports of the unit finance changes51 (employee)
Files touched by "overtime after 7h"1 (shared helper)1 (payroll/payroll.go)
Actors affected by "overtime after 7h"2 (finance + audit)1 (finance)
Can pay be tested without database/sql?No (same package)Yes
Fan-in of employeen/a3

Step 6: repeat the change. Set OvertimeThreshold = 7.0 in payroll. Expected: hoursreport output is unchanged.

Step 7 (Laravel, optional). Take Before.php from the Laravel section and split it into the slots of the After file. Expected: the controller imports drop from 5 use lines to 2, and "change the invoice email" touches only SendInvoice.

Common misconceptions ​

BeliefReality
SRP means one method per classIt means one actor per module; many methods are fine
SRP means "do one thing""Do one thing" is a function-level rule; SRP is about reasons to change
Smaller classes are always betterOver-splitting causes shotgun surgery; merge what always changes together
All duplication must be removedAccidental duplication across actors should stay
Bug fixes are reasons to changeMartin: bug fixes are the programmer's responsibility, not the program's
SRP does not apply to Go (no classes)The package is Go's unit of change (Cheney)
SRP is a microservices ruleIt starts at the function and applies at every level
Coupling should be zeroModules must communicate; control the direction and number of dependencies
LCOM tells you the responsibilitiesIt finds structural clusters; only people (and git history) reveal actors
A utils package is harmlessCoincidental cohesion: it grows and changes for every reason

Cheat sheet ​

TopicRemember
DefinitionOne reason to change = one actor
Memorable formGather what changes for the same reasons; separate what changes for different reasons
RootsParnas 1972 information hiding; Constantine's coupling and cohesion (1974)
TestWrite the actor table; more than one actor per row = split
DuplicationMerge true duplication, keep accidental duplication
GoPackage = unit of change; internal/ to hide; cmd/<name> per binary; no utils
LaravelForm Request, Action, Policy, Job, Listener, Observer, Resource
MetricsLCOM, CBO, fan-in/fan-out from code; change coupling from git
MovesExtract Class, Move Method, Move Field, Split Phase, Inline Class
TeamsConway's law: one module, one owning team; CODEOWNERS
MicroservicesSplit by business capability, not by technical layer
DataOne writer per table, one owner per cache key prefix

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 — A class has 25 methods, all changed only by the payroll team. Does it violate SRP? Must-know ​

Answer

Answer: No. It has one actor and one reason to change. It may be hard to read, which is a different problem. See Reason to change.

2 — Two functions in different modules contain the same three lines. When should you merge them? Important ​

Answer

Answer: Only when the same actor owns both and they must always change together. If different actors own them, it is accidental duplication; merging couples the actors. See Accidental duplication.

3 — What is the difference between SRP and "a function should do one thing"? Must-know ​

Answer

Answer: "Do one thing" concerns abstraction levels inside a function. SRP concerns how many actors can demand changes to a module. See SRP is not "do one thing".

4 — Why does Cheney say package utils is a warning sign? Important ​

Answer

Answer: Its name describes no purpose, so anything lands in it; with many responsibilities it changes "frequently and without cause", and every importer feels it. See Cohesion.

5 — Which metric can reveal a hidden SRP violation that LCOM and CBO miss, and how do you get it? Good to know ​

Answer

Answer: Change (logical) coupling from version-control history: files that change in the same commits. Use code-maat or the git + SQLite query in Change coupling.

6 — What does Go's internal/ directory enforce? Must-know ​

Answer

Answer: A package under .../a/b/c/internal/... can be imported only by code rooted at .../a/b/c. It lets you refactor helpers without breaking other modules. See Package as the unit of change.

7 — Name the Laravel class you would use for: validation, a permission rule, slow work after the response, reacting to Order creation. Important ​

Answer

Answer: Form Request, Policy, Job, Observer (or an event Listener). See The Laravel angle.

8 — How does Conway's law relate to SRP? Important ​

Answer

Answer: Systems copy the communication structure of the organisation. If two teams share a module, it has two reasons to change. Align module boundaries with team ownership. See Conway's law.

9 — A feature always requires PRs to four microservices. What SRP failure is this? Important ​

Answer

Answer: Services split by technical layer instead of by actor: shotgun surgery across a network, a distributed monolith. See Microservices.

10 — What are the two refactoring moves you use most to fix an SRP violation, and what is the reverse move for over-splitting? Must-know ​

Answer

Answer: Extract Class and Move Method (Move Function); the reverse is Inline Class. See Refactoring moves.

Glossary ​

TermMeaning
Single Responsibility Principle (SRP)A module should have one and only one reason to change
Reason to changeAn independent source of change requests, usually a group of people
ActorA group of stakeholders who want the same changes; SRP asks for one actor per module
StakeholderOne person with an interest in the module's behaviour
Cohesion (binding)How strongly a module's parts belong together; functional is best, coincidental worst
CouplingThe degree to which changing one module forces changing another
Information hidingParnas 1972: each module hides one design decision likely to change
Separation of concernsDijkstra's term for keeping different concerns in different places
Accidental duplicationCode that looks the same but belongs to different actors
True duplicationThe same knowledge in two places; always change together
God classA class with many actors, high coupling and low cohesion
Fan-in / fan-outNumber of modules depending on this one / that this one depends on
LCOMLack of Cohesion of Methods: method pairs that share no fields
CBOCoupling Between Objects: number of classes a class depends on
Change coupling (logical coupling)Files that change together in version-control history
ChurnHow much a file changes over time
Shotgun surgeryOne change requires edits in many modules (over-split or wrong split)
Divergent changeOne module changes for many different reasons (the SRP violation itself)
Unit of changeThe smallest thing you edit, review, test and release together; the package in Go
Module boundaryThe line around code owned by one actor, with a narrow public API
FacadeOne simplified entry point to a subsystem (GoF); not Laravel's static facades
Common Closure Principle (CCP)Martin 2000: classes that change together belong together (package level)
Conway's lawSystems copy the communication structure of the organisation that builds them
Inverse Conway ManeuverShaping teams on purpose so the architecture follows
Team ownership / CODEOWNERSOne owning team per path, enforced by review rules
Bounded contextA DDD boundary inside which a model and its language are consistent
Distributed monolithServices that must change and deploy together
Extract ClassRefactoring: move part of a class into a new class
Move Method / Move FunctionRefactoring: move behaviour to the module that owns its data
Inline ClassRefactoring: merge a class that has no separate reason to exist
Split PhaseRefactoring: separate parse, compute and format stages with a data structure
Form Request / Action / Policy / Job / Listener / ObserverLaravel's slots for validation, use cases, authorization, queued work, event reactions and model-lifecycle reactions
internal/Go directory whose packages can be imported only from its parent tree
cmd/Go convention: one directory per binary, each a main package

References ​

Built by Morteza Negahi