Design Quality: Complexity, Coupling & Cohesion, Information Hiding, Separation of Concerns, Conceptual Integrity
"Every module in the second decomposition is characterized by its knowledge of a design decision which it hides from all others. Its interface or definition was chosen to reveal as little as possible about its inner workings." — D. L. Parnas, On the Criteria To Be Used in Decomposing Systems into Modules, Communications of the ACM 15(12), 1972
Summary: Good design is the art of keeping complexity low: few and weak dependencies between modules (low coupling), strong relationships inside each module (high cohesion), each likely-to-change decision hidden behind a small interface, each concern in its own place, and one consistent set of ideas across the whole system. Focus: Essential vs accidental complexity, Ousterhout's three symptoms, the full coupling and cohesion scales, information hiding vs encapsulation, interfaces as contracts, deep vs shallow modules, separation of concerns and cross-cutting concerns, conceptual integrity, connascence, metrics and tools, and how the same rules apply between microservices. Learning goal: Name the kind of coupling and cohesion in any piece of code, measure it, and move it one step toward "data coupling, functional cohesion, deep module" in Go and Laravel, inside a monolith and across services.
This page is the vocabulary chapter of the design section. Every later chapter uses its words: SRP is "cohesion around one actor", ISP is "narrow interfaces", DIP is "point dependencies at stable abstractions", the Law of Demeter is "do not reach through other objects' internals", and most entries in Code Smells & Refactoring are named symptoms of high coupling or low cohesion. Here we define the measures themselves, where they come from, how to measure them, and how to fix them. The step from classes to services is drawn in In architecture and continued in Service Boundaries and Modular Monolith.
Page map
| If you are looking for | Go to |
|---|---|
| Every principle on one screen | Everything in one minute |
| Why any of this costs or saves money | Why design quality matters |
| Parnas, Constantine, Brooks, Dijkstra, McCabe, Ousterhout, Page-Jones | Where it comes from |
| Complexity and its symptoms | Complexity, Essential vs accidental |
| The coupling scale, temporal coupling, Ca/Ce/instability | Coupling, Temporal coupling, Afferent, efferent, instability |
| The cohesion scale | Cohesion |
| Information hiding, encapsulation, interfaces, deep modules | Information hiding, Interfaces as contracts, Deep vs shallow |
| Separation of concerns, cross-cutting concerns | Separation of concerns |
| Conceptual integrity and how teams lose it | Conceptual integrity |
| Connascence: name, type, meaning, position, algorithm, execution, timing, value, identity | Connascence |
| Cyclomatic complexity, LCOM, fan-in/out, gocyclo, go-arch-lint, phpmetrics, deptrac | Mechanics |
| Before/after code | Go, Laravel |
| Globals, flags, shallow wrappers, shared tables, chatty calls | Solving the classic problems |
| Shared DB, chatty APIs, temporal coupling between services | In architecture |
| Hands-on measurement | Lab |
Everything in one minute
The principles. Each row is unpacked in the concept catalogue.
| Principle | In plain words | Symptom when missing | First fix |
|---|---|---|---|
| Low complexity | The system is easy to understand and change | A one-line feature takes a week | Remove dependencies and obscurity |
| Low coupling | Changing A rarely forces changing B | "I only touched X and Y broke" | Pass data, not flags or globals |
| High cohesion | Everything in a module belongs together | utils, helpers, Manager classes | Move code next to its only user |
| Information hiding | Each module hides one decision likely to change | Callers know your table names, lock, retry policy | Shrink the interface |
| Deep modules | Small interface, lots of hidden functionality | Pass-through wrappers, classitis | Merge shallow pieces, pull complexity down |
| Separation of concerns | Different concerns live in different places | Auth, logging and rules in one function | Middleware, layers, events |
| Conceptual integrity | The whole system reflects one set of ideas | Three ways to paginate, two error formats | One architect role, ADRs, style guide |
| Weak connascence | What must change together is named and close | Magic numbers, positional args across modules | Named types, constructors, keep it local |
The coupling scale (tightest first). Full block: Coupling.
| Level | What is shared | Tiny example |
|---|---|---|
| Content (pathological) | Internals: code or private data of the other module | Reflection on private fields; SQL into another module's tables |
| Common | Global mutable data | var DB *sql.DB, config() read deep inside logic |
| External | An imposed format, protocol or device | Two modules parse the same CSV layout |
| Control | A flag that picks the callee's branch | Render(o, true, false) |
| Stamp | A whole structure, partly used | Passing an Eloquent model to read id |
| Data | Only the elementary values needed | Total(lines, "EUR") |
The cohesion scale (weakest first). Full block: Cohesion.
| Level | Why the parts are together | Tiny example |
|---|---|---|
| Coincidental | No reason | helpers.php |
| Logical | Same category, chosen by a flag | Exporter::export($type) |
| Temporal | Run at the same moment | boot() that does five unrelated things |
| Procedural | Steps of one procedure on different data | "check permission, then open file" |
| Communicational | Work on the same data | Every method reads the same Order |
| Sequential | Output of one is input of the next | parse → validate → normalise |
| Functional | All parts serve one well-defined task | CurrencyConverter::convert |
What you can measure. Full block: Mechanics.
| Metric | Measures | Go tool | PHP tool |
|---|---|---|---|
| Cyclomatic complexity | Independent paths through a function | gocyclo, golangci-lint (gocyclo linter) | phpmetrics (ccn) |
| LCOM | Methods that share no fields | none built in | phpmetrics (lcom) |
| Fan-in / fan-out | Who uses me / whom I use | go list -deps, import graph | phpmetrics (afferent/efferent) |
| Ca, Ce, Instability I = Ce / (Ca + Ce) | Package stability | import graph script | phpmetrics (instability) |
| Forbidden dependencies | Architecture rules | go-arch-lint | deptrac, Pest arch() |
| Change coupling | Files that change together | git log analysis | git log analysis |
Why design quality matters
Every program has to be understood before it can be changed. The cost of a change is mostly the cost of finding out what else must change and being sure nothing else breaks. Design quality is the set of properties that keep that cost low as the system grows. Stevens, Myers and Constantine put it in one sentence in 1974: "Simplicity is the primary measurement recommended for evaluating alternative designs relative to reduced debugging and modification time." Ousterhout's course notes say the same in modern words: complexity is "anything related to the structure of a system that makes it hard to work on the development of that system."
| Optimising for "works today" | Optimising for "easy to change" |
|---|---|
| Fastest first commit | Slightly slower first commit |
| Call whatever you can reach | Call only published interfaces |
| Globals and flags are convenient | Dependencies are passed explicitly |
| Each feature adds its own style | One style, written down |
| Cost grows with every change | Cost grows slowly |
| Risk: big ball of mud | Risk: over-engineering, too many layers |
Fowler's Design Stamina Hypothesis (bliki) frames the trade: below a certain point, skipping design is faster; above it, the lack of design makes every feature slower. The point comes earlier than most teams expect.
The analogy we reuse on this page: the electrical wiring of a building. The wires are inside the walls (information hiding); you use a standard socket, not the copper (an interface as a contract); a socket hides a lot behind a tiny face (a deep module); each room has its own circuit so a kettle cannot black out the server room (low coupling, separation of concerns); each circuit powers related things (cohesion); one electrician's plan with one colour code covers the whole building (conceptual integrity). Splice a wire from the neighbour's flat into yours and you have content coupling.
Three common misunderstandings, up front
- "Low coupling means no dependencies." Fowler, Reducing Coupling (IEEE Software, 2001): "if you ban coupling between modules, you have to put everything in one big module." The goal is weak, few, one-directional dependencies, not zero.
- "Small classes mean good design." Ousterhout calls the extreme "classitis": many shallow classes, each adding a tiny bit of function behind its own interface. Depth matters more than size.
- "Encapsulation and information hiding are the same thing." Making fields
privateis a language mechanism. Information hiding is a design decision about what to hide. Private fields with public getters and setters for each one hide nothing.
Where it comes from
Dijkstra, 1974: separation of concerns. In EWD447, On the role of scientific thought, Dijkstra describes studying "an aspect of one's subject matter in isolation for the sake of its own consistency" and names it:
"It is what I sometimes have called "the separation of concerns", which, even if not perfectly possible, is yet the only available technique for effective ordering of one's thoughts, that I know of." — E. W. Dijkstra, On the role of scientific thought (EWD447), 1974
Parnas, 1972: information hiding. Parnas compared two decompositions of the same KWIC index program. The conventional one followed the flowchart; his followed the decisions that might change. His conclusion:
"We propose instead that one begins with a list of difficult design decisions or design decisions which are likely to change. Each module is then designed to hide such a decision from the others." — D. L. Parnas, 1972
Stevens, Myers and Constantine, 1974: coupling and cohesion. Structured Design (IBM Systems Journal 13(2)) defined coupling as "the measure of the strength of association established by a connection from one module to another" and stated that "Coupling is lower with data connections than with control connections, which are in turn lower than hybrid connections (modification of one module's code by another module)." It called cohesion binding and ranked it in six levels: "1. Coincidental. 2. Logical. 3. Temporal. 4. Communicational. 5. Sequential. 6. Functional." adding that "The scale is not linear." Larry Constantine had developed the ideas in the late 1960s; the book by Yourdon and Constantine (1975/1979) made them standard (secondary source: Wikipedia, Coupling (computer programming)). The six-level coupling list used today (content, common, external, control, stamp, data) is the later textbook form from Myers and Page-Jones; Page-Jones's Practical Guide to Structured Systems Design (1980/1988) calls content coupling "pathological" (we read this in Tony Barrett-Powell's ACCU 2010 slides that cite the book, not in the book itself). Procedural cohesion appears in the later texts, giving seven levels.
Brooks, 1975: conceptual integrity. Chapter 4 of The Mythical Man-Month, "Aristocracy, Democracy, and System Design":
"I will contend that conceptual integrity is the most important consideration in system design. It is better to have a system omit certain anomalous features and improvements, but to reflect one set of design ideas, than to have one that contains many good but independent and uncoordinated ideas." — F. P. Brooks, The Mythical Man-Month, ch. 4
McCabe, 1976: cyclomatic complexity. A Complexity Measure (IEEE TSE, December 1976) took the cyclomatic number of the control-flow graph, v = e - n + 2p, as a measure of a module, and reported a practical rule: "The particular upper bound that has been used for cyclomatic complexity is 10 which seems like a reasonable, but not magical, upper limit."
Brooks, 1986: essence and accident. No Silver Bullet divides difficulties "into essence—the difficulties inherent in the nature of the software—and accidents—those difficulties that today attend its production but that are not inherent," and argues that the complexity of software is an essential property, not an accidental one.
Martin, 1994–2000: package metrics. Design Principles and Design Patterns (2000) defines afferent coupling Ca, efferent coupling Ce and instability I = Ce / (Ca + Ce), and the rule "Depend upon packages whose I metric is lower than yours."
Page-Jones, 1990s: connascence. Meilir Page-Jones introduced connascence as a finer vocabulary for coupling; the definitions we use come from connascence.io, which describes it as "a software quality metric & a taxonomy for different types of coupling" judged on strength, degree and locality.
Fowler, 2001. Reducing Coupling: "If changing one module in a program requires changing another module, then coupling exists," and "Duplication always implies coupling."
Ousterhout, 2018. A Philosophy of Software Design and his Stanford CS 190 notes give the modern working vocabulary: complexity has three symptoms (change amplification, cognitive load, unknown unknowns) and two causes (dependencies and obscurity), and "Classes Should be Deep". The notes call information hiding "the single most important idea in software design".
The concept catalogue
Each block: plain words, the usual wrong belief, a precise definition, a change timeline, real scenarios, and the fix.
Complexity Must-know
In plain words: complexity is whatever makes the code hard to understand and change for the person working on it now.
Common misunderstanding: "Complexity means a big system." Ousterhout's notes: it "Doesn't necessarily correlate with system size or number of features." A small codebase full of hidden dependencies is more complex than a large, well-split one.
Definition: Ousterhout's three symptoms, verbatim from his CS 190 notes:
| Symptom | Ousterhout's wording | What you see |
|---|---|---|
| Change amplification | "a simple change requires many code modifications" | Changing the currency format edits 14 files |
| Cognitive load | "have to load a lot of information in your mind in order to make a change" | You must know the lock order, the cache key format and the retry policy to add one endpoint |
| Unknown unknowns | "there's important information you need to know before making a change, but not obvious where to find it, or even that it is needed" | A report breaks because it read your table directly; nothing in your code mentioned it |
and two causes: dependencies ("If one changes, the other must change also") and obscurity ("not clear how things work or why the code is the way it is"). "Complexity is incremental": no single commit does it; thousands of small dependencies do.
Week Change request Files touched Symptom
1 W1 add "GBP" currency 1 none
2 W8 add "GBP" currency (after 30 copies 14 change amplification
of formatMoney() were pasted around)
3 W9 reviewer must know cache keys embed - cognitive load
the currency and the invoice PDF caches by them
4 W10 finance report breaks: it parsed the - unknown unknown
old money string in SQL; nobody knewReal scenario: a pricing rule duplicated in the API, the admin panel and a nightly job; a Go service where every handler must remember to call tx.Rollback() in the same order; a Laravel app where the meaning of status = 3 is known only to the original author.
Fix: reduce dependencies (fewer, weaker connections: the coupling block) and reduce obscurity (names, types and comments that make the first guess correct: the connascence block).
Essential vs accidental complexity Important
In plain words: essential complexity is in the problem (tax law is complicated); accidental complexity is what we added while solving it (three caching layers nobody needs).
Common misunderstanding: "Good design removes complexity." It removes accidental complexity and contains the essential kind behind a small interface. Brooks: descriptions "that abstract away its complexity often abstract away its essence."
Definition: Brooks (1986) splits software work into "essential tasks, the fashioning of the complex conceptual structures that compose the abstract software entity, and accidental tasks, the representation of these abstract entities in programming languages." Design quality work targets the accidental part and places the essential part in one deep module.
| Example | Essential | Accidental |
|---|---|---|
| VAT across 27 EU countries | Rates, reverse charge, thresholds | The rule copied into 4 services |
| Exchange rates | Rates change; providers fail | Every caller handles caching and retries itself |
| Order state machine | Allowed transitions | Status codes as magic integers |
| Distributed checkout | Partial failure is real | A synchronous chain of 6 services that all must be up |
Fix: move the essential complexity down into one module (Ousterhout's "pull complexity down"), and delete the accidental complexity around it.
Coupling Must-know
In plain words: coupling is how much a change in one module forces a change, a retest or extra knowledge in another.
Common misunderstanding: "If there is an interface between them, they are decoupled." An interface whose methods take a mode int flag, return the whole database row, or require calls in a fixed order is still tightly coupled. Coupling is about what crosses the boundary, not whether a keyword is used.
Definition: Stevens, Myers and Constantine: "the measure of the strength of association established by a connection from one module to another." It depends "(1) on how complicated the connection is, (2) on whether the connection refers to the module itself or something inside it, and (3) on what is being sent or received."
The picture shows the six classic levels, tightest on the left, and two forms that do not show up in a call graph: temporal coupling and change coupling.
| Level | Definition | Go example | Laravel example | Fix |
|---|---|---|---|---|
| Content (pathological) | One module uses or modifies the internals of another | unsafe/reflect to set a private field; importing another team's internal by copying it | DB::table('billing_payments') from the reporting module | Call the owner's published API |
| Common | Several modules share global data | var DB *sql.DB, package-level Currency | config() read inside domain logic; a shared settings table | Pass dependencies explicitly; read config at the edge |
| External | Shared externally imposed format, protocol or device | Two packages hand-parse the same fixed-width file | Two jobs build the same partner XML by hand | One adapter owns the format |
| Control | Caller passes a flag that selects behaviour | Render(o, asCSV, withNotes) | export($order, 'pdf') with a match inside | Split into named functions (CSV, Text) |
| Stamp (data-structured) | A whole structure is passed, only part used | func Total(o *Order) reading only Lines | Passing a User model to read id | Pass the smallest type: []Line, int $userId, a DTO |
| Data | Only elementary values or small value objects | Total(lines []Line, cur string) Money | new OrderSummary($id, $paid, $cur) | The target |
Stevens et al. on control coupling: "an alternative structure that eliminates the complication always exists." On the timeline, a control flag spreads like this:
Step Change Modules edited
1 v1 Render(o, asCSV) report
2 v2 product asks for notes in CSV only report + 3 callers (new bool)
3 v3 add JSON: asCSV becomes format string report + 3 callers again
4 v4 a caller passes "cvs"; falls into default runtime bug, no compile error
5 fix CSV(s), Text(s), JSON(s): caller picks by name each new format edits 1 moduleReal scenario: a Go utils.DB global swapped in tests and forgotten, so a later test talks to the wrong database; a Laravel ReportService::generate($type, $options) whose $options array is understood only by reading 400 lines; a mobile app and backend sharing a JSON shape nobody owns (external coupling without a contract).
Fix: move one step right on the scale at a time. Code: Go before/after, Laravel before/after.
Temporal coupling Important
In plain words: two things are temporally coupled when they must happen in a certain order or at the same time for the system to work.
Common misunderstanding: "Temporal coupling and temporal cohesion are the same." Temporal cohesion is a reason for grouping code (it runs at startup). Temporal coupling is a dependency in time between modules: "call Init before Send", or "the payment service must be up when checkout runs."
Definition: in code, it is connascence of execution order (see connascence): the correct order is not enforced by the types. Between services, it is the dependency created by synchronous calls: the caller works only while the callee is up and fast. Wikipedia's coupling article (secondary) also uses the name for actions bundled together "because they happen to occur at the same time."
t checkout (sync HTTP) payments service
1 0ms POST /charge ------------------------> up
2 40ms 200 OK <------------------------
3 ... deploy of payments starts
4 0ms POST /charge ------------------------> restarting
5 5s timeout; checkout returns 502 -- checkout availability = its own x payments'
6 fix write order + outbox row, return 202; payments consumes OrderPlaced when back upReal scenario: a Go struct with Init() that callers forget; a Laravel listener that must run after another listener because it reads a column the first one writes; a chain of HTTP calls where each service's availability multiplies (0.99 × 0.99 × 0.99 ≈ 0.97).
Fix: in code, make the invalid order unrepresentable (a constructor that returns a ready object). Between services, replace the call with a message (outbox + broker) when the caller does not need the answer now. See Go connascence and Microservices.
Afferent, efferent coupling and instability Important
In plain words: afferent coupling (Ca) counts who depends on me; efferent coupling (Ce) counts whom I depend on. Instability says how easily a package is pushed around by others.
Common misunderstanding: "Instability is bad." Martin (2000): "we greatly desire that portions of our software be instable." UI and adapters should be unstable (easy to change); core policies should be stable. The bug is a stable package depending on an unstable one.
Definition: Martin, Design Principles and Design Patterns: "Ca Afferent Coupling. The number of classes outside the package that depend upon classes inside the package"; "Ce Efferent Coupling. The number of classes outside the package that classes inside the package depend upon"; I = Ce / (Ca + Ce), range 0 (stable) to 1 (unstable). The Stable Dependencies Principle: "Depend upon packages whose I metric is lower than yours." phpmetrics reports exactly these three as afferentCoupling, efferentCoupling, instability.
| Package (lab numbers) | Ca | Ce | I | Verdict |
|---|---|---|---|---|
orders (consumer interface) | 1 (cmd) | 0 project packages | 0.0 | Stable core, as wanted |
stripepay | 1 (cmd) | 0 project packages | 0.0 | Leaf adapter |
cmd | 0 | 2 | 1.0 | Composition root: unstable by design |
orders (before) | 0 | 1 (stripepay) | 1.0 | Core depends on a vendor adapter: SDP violation in spirit |
Fan-in and fan-out are the same idea per function or class (CK tool: FAN-IN is "the number of input dependencies a class has").
Cohesion Must-know
In plain words: cohesion is how strongly the parts of one module belong together. High cohesion means a change usually stays inside one module.
Common misunderstanding: "Putting all the string helpers together is cohesive: they are all about strings." That is logical cohesion, the second-weakest level. The question is not "are these the same kind of thing?" but "do they serve the same task and change for the same reason?"
Definition: Stevens et al.: "Binding is the measure of the cohesiveness of a module. The objective here is to reduce coupling by striving for high binding." Cohesion and coupling are two sides of one decision: "minimizing the relationships among modules and maximizing relationships among elements in the same module."
| Level | Elements are together because | Go example | Laravel example | Move to fix |
|---|---|---|---|---|
| 1 Coincidental | No reason | package utils with Slugify, Retry, TaxRate | app/helpers.php | Move each function to its only user or a purposeful package |
| 2 Logical | Same category, selected by a flag | Export(kind string) with a switch | ExportService::run($type) | One type per variant behind an interface |
| 3 Temporal | Executed at the same time | func boot() opens DB, warms cache, pings Slack | One AppServiceProvider::boot() doing everything | Each module registers its own startup |
| 4 Procedural | Steps of one procedure, unrelated data | checkPermThenOpenFile() | Controller method that authorizes then formats a CSV | Split by data |
| 5 Communicational | Operate on the same data | Methods all on one Order | Model methods on one Order | Usually fine |
| 6 Sequential | Output of one feeds the next | parse → validate → normalise | Pipeline (Illuminate\Pipeline) stages | Fine; watch the stage interfaces |
| 7 Functional | All contribute to one task | cache.Get/Set | CurrencyConverter::convert | The target |
Request With package utils With purposeful packages
1 change slug rules for SEO edit utils/strings.go edit slug/slug.go
2 -- 40 packages import utils: all rebuild, all retest, review needs 3 teams --
3 change retry backoff for HTTP edit utils/retry.go edit httpclient/retry.go
4 a new hire looks for "tax rate" greps utils, finds 2 copies finds tax/rates.goBefore/after (cohesion): utils.Slugify, utils.Retry, utils.TaxRate → slug.Make, httpclient.Retry, tax.Rate. Dave Cheney's rule for Go applies: a package name must describe its purpose, so utils, common, helpers, misc are warnings.
Information hiding and encapsulation Must-know
In plain words: information hiding means deciding which design decisions other modules must never depend on, and keeping them inside one module. Encapsulation is the language feature (private fields, unexported names) you use to enforce it.
Common misunderstanding: "My fields are private, so I have information hiding." If the class has a getter and setter for every field, or its method names reveal the storage (getRowsFromMysql), the decision is leaked even though the fields are private. Ousterhout: "Using classes does not necessarily guarantee information hiding!"
Definition: Parnas: each module hides "a design decision which it hides from all others," with an interface "chosen to reveal as little as possible about its inner workings." Ousterhout names the opposite information leakage: "Implementation details exposed, other classes depend on them," including "Back-door leakage: not visible in the interface" (two modules that both know a file format). He names a common cause, temporal decomposition: "Code structure reflects the order in which operations execute" (exactly Parnas's flowchart decomposition).
| Information hiding | Encapsulation | |
|---|---|---|
| Kind | Design principle | Language mechanism |
| Question | Which decisions may change, and who must not know them? | Which names are visible outside? |
| Go | Package boundary, internal/, small exported API | Lowercase identifiers are unexported |
| PHP | Module boundary, contract interface, @internal + deptrac rule | private, protected, readonly |
| Fails when | Interface mirrors implementation | Getters/setters for everything; reflection |
Change Leaky module (exports map + mutex) Hiding module (Get/Set)
1 switch eviction from FIFO to LRU 12 callers edited cache.go only
2 add metrics on hit rate every caller adds counters cache.go only
3 shard the map to cut lock contention impossible without touching callers cache.go onlyReal scenario: the database schema (hide it behind a repository; see Data Persistence in Design); the exchange-rate provider; the file layout of an export; the retry policy of an HTTP client; the queue technology behind "send later".
Fix: list the decisions likely to change (Parnas's method), give each one a module, and expose only what callers need. Code: Go deep cache, Laravel CurrencyConverter.
Interfaces as contracts Must-know
In plain words: an interface is everything a caller must know to use a module correctly: not only the method signatures but also the behaviour, errors, ordering rules and performance it can rely on.
Common misunderstanding: "The interface is the interface keyword." Ousterhout splits it into formal parts ("method signatures, public variables") and informal parts ("overall behavior, side effects, constraints on usage"), and the informal parts "can only be described with comments." A Go function that returns ErrEmptyCart has that error in its contract whether or not you wrote it down.
Definition: a contract has preconditions (what the caller must guarantee), postconditions (what the module guarantees), invariants, error behaviour, and non-functional promises (idempotency, latency, thread safety). The Liskov Substitution page covers the substitution rules; ISP covers keeping each interface narrow. Go Code Review Comments gives the Go placement rule: "Go interfaces generally belong in the package that uses values of the interface type, not the package that implements those values. The implementing package should return concrete (usually pointer or struct) types." Laravel's docs describe its contracts as "a set of interfaces that define the core services provided by the framework."
| Contract part | Go | Laravel / PHP | Between services |
|---|---|---|---|
| Signature | Method set | Interface methods, types | OpenAPI path, protobuf message |
| Errors | Sentinel errors, errors.Is | Typed exceptions | Status codes, error body schema |
| Behaviour | Doc comment | PHPDoc | API docs, examples |
| Ordering / lifecycle | Constructor returns ready value | Container binding, constructor | Idempotency keys, versioning |
| Concurrency | "safe for concurrent use" | (usually single request) | Rate limits, at-least-once delivery |
Fix: declare the interface where it is consumed, keep it small, document the informal parts, and test it with contract tests. Code: Go consumer-side interface, Laravel contract + provider.
Deep vs shallow modules Must-know
In plain words: a deep module gives you a lot of functionality behind a small interface; a shallow module makes you learn almost as much as it saves you.
Common misunderstanding: "Splitting a class into many small classes always lowers complexity." Every class adds an interface someone must learn. Ousterhout: "Many courses teach students that 'classes should be small': results in shallow classes," and "Classitis: small classes taken to the extreme."
Definition: Ousterhout's notes: "Deep class: small interface, lots of functionality"; shallow class: "Complex interface and/or not much functionality. Invoking a method isn't much easier than just typing in the code of the method." His canonical deep example is Unix file I/O (open, read, write, lseek, close hide disk layout, caching, permissions and devices). His red flag is the pass-through method, which forwards a call with the same signature and adds no abstraction ("Each layer's abstraction should be different from the layer above it and the layer below it").
The top edge of each box is the interface (what you must learn); the area is the functionality (what you get). The deep cache exposes Get and Set; the shallow one exposes its mutex, its map and an expiry helper.
| Signal | Deep | Shallow |
|---|---|---|
| Interface vs implementation size | Much smaller | About the same |
| Callers repeat setup or protocol | No | Yes |
| Can change implementation freely | Yes | No, callers depend on it |
| Typical form | CurrencyConverter::convert, io.Reader, net/http.Client.Do | Getter/setter classes, XRepositoryInterface that mirrors Eloquent, pass-through services |
Fix: merge shallow pieces that are always used together, pull repeated caller code into the module, and make general-purpose interfaces ("somewhat generic", in Ousterhout's words) for today's needs.
Separation of concerns and cross-cutting concerns Must-know
In plain words: each concern (business rule, HTTP, persistence, security, logging) is handled in its own place, so you can think about and change one without the others.
Common misunderstanding: "Separation of concerns means layers: controller, service, repository." Layers are one way to separate technical concerns. Dijkstra meant any aspect you can study "in isolation for the sake of its own consistency": correctness vs efficiency, policy vs mechanism, a pricing rule vs its HTTP transport. Splitting by layer while mixing two business concerns in one service is still a violation.
Definition: a concern is an aspect of the system with its own reason to change. A cross-cutting concern is one that applies to many modules at once: logging, authentication, authorization, metrics, tracing, transactions, caching, rate limiting, input validation. Scattered by hand, they produce tangling (many concerns in one function) and scattering (one concern in many functions). The usual tools are middleware/decorators, framework hooks, events, and in some languages aspect-oriented programming (AspectJ, Spring AOP).
Change request Tangled handler Middleware + pure rule
1 switch logging to slog JSON edit every handler edit Logging middleware
2 rotate API token header name edit every handler edit RequireToken
3 change 10% discount to 12% edit handler (risk: breaks auth path) edit TotalCents, unit test only
4 add tracing span per request edit every handler add one middleware| Cross-cutting concern | Go | Laravel |
|---|---|---|
| Authentication | func(http.Handler) http.Handler middleware | Middleware (auth:sanctum, custom) |
| Authorization | Middleware or explicit check in use case | Policies, Gates |
| Logging / tracing | Middleware, log/slog, OpenTelemetry handlers | Middleware, log context, Telescope/Pulse |
| Transactions | Use-case function with db.BeginTx | DB::transaction in the action |
| Validation | Decode + validate in handler adapter | Form Requests |
| Caching | Decorator around an interface | Cache::remember inside a deep module |
| Side effects after a fact | Publish an event | Events + queued listeners |
Fix: keep business rules free of transport and I/O; put cross-cutting concerns in middleware or decorators; let reactions subscribe to events. Code: Go middleware, Laravel middleware, Laravel events.
Conceptual integrity Important
In plain words: the whole system feels like it was designed by one mind: one way to name things, one way to handle errors, one way to paginate, one model of the domain.
Common misunderstanding: "Conceptual integrity means one person writes everything." Brooks separates architecture (the external specification) from implementation and says the design "must proceed from one mind, or from a very small number of agreeing resonant minds" while the implementation still needs many hands. "The design of an implementation, given an architecture, requires and allows as much design creativity."
Definition: Brooks: "Simplicity and straightforwardness proceed from conceptual integrity. Every part must reflect the same philosophies and the same balancing of desiderata." And on features that do not fit: "Good features and ideas that do not integrate with a system's basic concepts are best left out."
How teams lose it:
| Cause | What it looks like | Countermeasure |
|---|---|---|
| Many authors, no owner of the concepts | Three pagination styles: ?page=, ?offset=, cursor | An architect role or design authority for the external spec |
| Feature-by-feature growth | Each endpoint invents its own error JSON | One error format (e.g. RFC 9457 problem details), enforced in middleware |
| Team turnover | New team re-solves an old problem differently | ADRs that record the decision and its reason |
| Framework mixing | Half the app uses Eloquent, half raw SQL with arrays | A written "how we do X here" guide and lint rules |
| Microservices without a platform | Each service has its own auth, logging, config style | Paved road / shared libraries, API style guide |
| Copying from the internet | Patterns that fight the framework | Review against the guide, not taste |
Before/after (conceptual integrity):
Before After (one API style guide)
1 GET /orders?page=2&per_page=20 GET /orders?cursor=abc&limit=20
2 GET /customers?offset=40&limit=20 GET /customers?cursor=def&limit=20
3 GET /invoices/list/3 GET /invoices?cursor=ghi&limit=20
4 errors: {"error":"x"}, {"message":"x"}, "x" errors: application/problem+json everywhereFix: write down the few decisions that every part must share (naming, errors, pagination, IDs, time zones, money, auth), record why in ADRs (see Architecture Decisions), and say "no" to features that do not fit. This is also why Architecture vs Design puts the architect role where it is.
Connascence Good to know
In plain words: two pieces of code are connascent when changing one requires changing the other to keep the program correct. Connascence names what kind of agreement they share.
Common misunderstanding: "Connascence is just another word for coupling." It is a finer scale with three axes. Two modules can both be "data coupled" while one pair agrees only on a name (easy to change) and the other agrees on the order of five positional arguments (fragile).
Definition: connascence.io: "Connascence is a software quality metric & a taxonomy for different types of coupling," judged on strength ("the ease with which that type of coupling can be refactored"), degree ("Does the coupling in question affect 2 entities, or 200?") and locality ("Code that is close together ... should typically have more, and higher forms of connascence than code that is far apart"). "Static connascences are considered to be weaker than dynamic connascences."
| Form (weak to strong) | Static / dynamic | Two pieces must agree on | Example | Weaker alternative |
|---|---|---|---|---|
| Name | Static | A name | Calling Charge | (already weakest) |
| Type | Static | A type | int cents vs float euros | Value types (Money) |
| Meaning (convention) | Static | What a value means | role == 2 means admin; "9999-9999-9999-9999" is a test card | Named constants, enums |
| Position | Static | Order of values | New(name, email, true, false, 2) | Named fields, options struct |
| Algorithm | Static | The same algorithm | Client and server both compute an HMAC or checksum | One shared function or library |
| Execution (order) | Dynamic | Order of execution | Init() before Send() | Constructor returns ready object |
| Timing | Dynamic | Timing of execution | Race between cache write and read; timeout assumptions | Synchronisation, idempotency |
| Value | Dynamic | Values that must stay consistent | Two replicas of a price; a cached total | Single source of truth, derive |
| Identity | Dynamic | Reference the same instance | Two services must update the same row | One owner, IDs not object references |
Step Connascence Degree Locality Action
1 role == 2 in 30 places meaning 30 across 6 packages high risk: refactor
2 → const Admin Role = 2 name 30 across 6 packages safe: rename is mechanical
3 New(name, email, true, false, 2) position 12 across 3 packages refactor to User{...}
4 two locals in one 10-line func position 1 same function leave it: local and visibleRule of thumb: convert strong forms to weaker ones (connascence of meaning or position becomes connascence of name or type), reduce degree, and keep whatever strong connascence remains local (inside one function or package). Code: Go connascence before/after.
Per-language and per-tool view
| Language / framework | Unit of hiding | Interface mechanism | Boundary enforcement | Metrics and rules |
|---|---|---|---|---|
| Go | Package (internal/ for module-private) | Implicit interfaces, declared by the consumer | Compiler: unexported names, internal/, no import cycles | gocyclo, gocognit, golangci-lint, go-arch-lint, go list -deps |
| PHP / Laravel | Class + module folder or Composer package | interface, Laravel contracts, container bindings | private/readonly, deptrac layers, Pest arch() tests | phpmetrics, PHPStan/Larastan, deptrac |
| Java / Spring | Package + JPMS module | interface, Spring beans | Package-private, module-info.java, ArchUnit | CK (CBO, LCOM, FAN-IN/OUT), SonarQube |
| C# / .NET | Assembly | interface, DI container | internal, project references, NetArchTest | Visual Studio code metrics (class coupling, cyclomatic) |
| TypeScript | ES module + package | Structural types | exports map, eslint import rules, dependency-cruiser | dependency-cruiser, eslint complexity rule |
Mechanics
Cyclomatic complexity Important
McCabe's measure counts linearly independent paths through a function's control-flow graph: v(G) = e - n + 2p (edges, nodes, connected components). In practice tools count decisions. gocyclo's README states its rules: "1 is the base complexity of a function, +1 for each 'if', 'for', 'case', '&&' or '||'". McCabe's own limit was 10, "reasonable, but not magical." The metric measures testing paths, not understanding: a flat switch with 15 cases scores 16 and is easy to read; three nested loops with early returns may score 6 and be hard. Cognitive-complexity tools (SonarQube, gocognit) weight nesting to approximate readability.
go install github.com/fzipp/gocyclo/cmd/gocyclo@latest
gocyclo -over 10 ./... # exit code 1 if any function is above 10
gocyclo -top 10 -avg . # ten worst plus the averageLCOM: lack of cohesion of methods Good to know
LCOM counts how many method pairs of a class share no fields, minus those that do (Chidamber and Kemerer's first version) or, in later variants (LCOM*, LCOM-HS, LCOM4), how many disconnected groups the methods form. The CK tool's README warns that the first version "is not reliable." phpmetrics reports lcom and explains: "A non-cohesive class may need to be restructured into two or more smaller classes." Use it to find candidates, never as a gate: a cohesive class that delegates everything to one dependency scores well and can still be shallow.
Fan-in, fan-out and package metrics Important
| Metric | Formula | Healthy pattern | Unhealthy pattern |
|---|---|---|---|
| Fan-in (Ca) | modules that depend on this one | High on small, stable modules (money, time) | High on a module that changes weekly |
| Fan-out (Ce) | modules this one depends on | High only in composition roots (main, service providers) | High in domain code |
| Instability I | Ce / (Ca + Ce) | Dependencies point toward lower I | Stable core imports unstable adapter |
| Abstractness A | abstract types / all types | Stable packages are abstract | Stable and concrete ("zone of pain") |
| Distance D | abs(A + I - 1) | Near 0 ("main sequence") | Near 1 |
| Structural complexity (Card & Agresti, phpmetrics) | fan-out squared | Low | Grows fast with each call |
The DIP chapter draws the main-sequence diagram.
Architecture rules as tests Must-know
Metrics describe; rules prevent. Both ecosystems have a tool that fails CI when a forbidden import appears.
go-arch-lint reads .go-arch-lint.yml (from its README: "Linter used to enforce some good project structure and validate top level architecture (code layers)"):
version: 3
workdir: internal
components:
handler: { in: handlers/* }
service: { in: services/** }
repository: { in: domain/*/repository }
model: { in: models }
commonComponents:
- models
deps:
handler:
mayDependOn:
- service
service:
mayDependOn:
- repositorygo install github.com/fe3dback/go-arch-lint@latest
go-arch-lint check --project-path .deptrac for PHP ("helps you communicate, visualize and enforce architectural decisions"): define layers with collectors and a ruleset of who may use whom.
# deptrac.yaml: module boundaries for a Laravel modular monolith.
# Run: vendor/bin/deptrac analyse --config-file=deptrac.yaml
deptrac:
paths:
- ./app
layers:
- name: BillingContracts
collectors:
- type: directory
value: app/Modules/Billing/Contracts/.*
- name: BillingInternal
collectors:
- type: directory
value: app/Modules/Billing/Internal/.*
- name: Reporting
collectors:
- type: directory
value: app/Modules/Reporting/.*
- name: Http
collectors:
- type: directory
value: app/Http/.*
ruleset:
Http:
- BillingContracts
- Reporting
Reporting:
- BillingContracts
BillingInternal:
- BillingContracts
BillingContracts: ~composer require --dev deptrac/deptrac
vendor/bin/deptrac analyse --config-file=deptrac.yaml
composer global require 'phpmetrics/phpmetrics'
phpmetrics --report-html=report ./app # ccn, lcom, afferent/efferent coupling, instabilityChange coupling from git Good to know
Static tools see imports; they cannot see two files with no import between them that always change together (shared knowledge, external coupling, back-door leakage). The SRP chapter has the git + SQLite query; run it per module folder and read high scores across module boundaries as hidden coupling.
Tool table Good to know
| Tool | Language | Measures / enforces | Typical CI gate |
|---|---|---|---|
| gocyclo | Go | Cyclomatic complexity per function | gocyclo -over 15 ./... |
| gocognit | Go | Cognitive complexity | via golangci-lint |
| golangci-lint | Go | Runs gocyclo, gocognit, depguard and more | golangci-lint run |
| go-arch-lint | Go | Allowed dependencies between components | go-arch-lint check |
| phpmetrics | PHP | ccn, lcom, Ca/Ce/instability, maintainability index | HTML report, thresholds by script |
| deptrac | PHP | Allowed dependencies between layers | vendor/bin/deptrac analyse |
Pest arch() | PHP | Expectations such as "App\Modules\Billing may not be used by X" | ./vendor/bin/pest --filter=arch |
| PHPStan / Larastan | PHP | Types (reduces connascence of type surprises) | phpstan analyse |
Go
Coupling: before and after
The before package shares a global DB and Currency (common coupling), takes the whole *Order to read Lines (stamp coupling), and decides its output by two booleans (control coupling).
// Package report is the "before" side of the coupling scale.
// It compiles and works, but it shows common, stamp and control coupling.
package report
import (
"context"
"database/sql"
"fmt"
)
// DB is common coupling: every importer can read or replace it.
var DB *sql.DB
// Currency is common coupling too: a global that silently changes output.
var Currency = "EUR"
// Order is the full record. Callers that need two fields still get all of it.
type Order struct {
ID int64
CustomerEmail string
ShippingAddress string
Notes string
Lines []Line
TotalCents int64
}
// Line is one order line.
type Line struct {
SKU string
Qty int
PriceCents int64
}
// LoadOrder depends on the package-level DB (common coupling).
func LoadOrder(ctx context.Context, id int64) (*Order, error) {
o := &Order{ID: id}
err := DB.QueryRowContext(ctx,
`SELECT customer_email, shipping_address, notes FROM orders WHERE id = $1`, id).
Scan(&o.CustomerEmail, &o.ShippingAddress, &o.Notes)
if err != nil {
return nil, err
}
return o, nil
}
// Total takes the whole Order (stamp coupling) and mutates it as a side effect.
func Total(o *Order) {
o.TotalCents = 0
for _, l := range o.Lines {
o.TotalCents += int64(l.Qty) * l.PriceCents
}
}
// Render is control coupled: the caller passes a flag that picks the branch.
func Render(o *Order, asCSV bool, withNotes bool) string {
if asCSV {
if withNotes {
return fmt.Sprintf("%d,%d,%s,%q\n", o.ID, o.TotalCents, Currency, o.Notes)
}
return fmt.Sprintf("%d,%d,%s\n", o.ID, o.TotalCents, Currency)
}
s := fmt.Sprintf("Order %d: %.2f %s", o.ID, float64(o.TotalCents)/100, Currency)
if withNotes && o.Notes != "" {
s += " (" + o.Notes + ")"
}
return s
}After: values in, values out. Store receives its connection; formatters are separate functions; Money keeps amount and currency together so they cannot drift (connascence of value made local).
// Package report is the "after" side: data coupling only, no globals, no flags.
package report
import (
"context"
"database/sql"
"fmt"
)
// Money is a value: amount and currency always travel together.
type Money struct {
Cents int64
Currency string
}
// Summary is the smallest structure the formatters need.
type Summary struct {
OrderID int64
Total Money
}
// Line is one order line.
type Line struct {
Qty int
Unit Money
}
// Total is data coupled: it receives exactly the data it needs and returns a value.
func Total(lines []Line, currency string) Money {
t := Money{Currency: currency}
for _, l := range lines {
t.Cents += int64(l.Qty) * l.Unit.Cents
}
return t
}
// CSV and Text replace the asCSV flag with two functions; the caller picks by name.
func CSV(s Summary) string {
return fmt.Sprintf("%d,%d,%s\n", s.OrderID, s.Total.Cents, s.Total.Currency)
}
// Text renders a human-readable line.
func Text(s Summary) string {
return fmt.Sprintf("Order %d: %.2f %s", s.OrderID, float64(s.Total.Cents)/100, s.Total.Currency)
}
// Store owns its connection; nobody else can swap it at runtime.
type Store struct {
db *sql.DB
}
// NewStore receives the dependency explicitly.
func NewStore(db *sql.DB) *Store { return &Store{db: db} }
// Summary loads only the columns the report needs.
func (s *Store) Summary(ctx context.Context, id int64) (Summary, error) {
out := Summary{OrderID: id}
err := s.db.QueryRowContext(ctx,
`SELECT total_cents, currency FROM orders WHERE id = $1`, id).
Scan(&out.Total.Cents, &out.Total.Currency)
return out, err
}Information hiding: shallow vs deep cache
// Package cache is a shallow module: its interface is almost as big as its body.
// Every caller must know about the mutex, the map and the expiry rule.
package cache
import (
"sync"
"time"
)
// Entry is exported, so its layout is part of the interface.
type Entry struct {
Value []byte
ExpiresAt time.Time
}
// Cache exposes its lock and its map (information leakage).
type Cache struct {
Mu sync.Mutex
Items map[string]Entry
}
// New returns an empty cache.
func New() *Cache { return &Cache{Items: map[string]Entry{}} }
// IsExpired forces callers to implement the expiry protocol themselves.
func (c *Cache) IsExpired(e Entry, now time.Time) bool { return now.After(e.ExpiresAt) }
// Usage that every caller has to repeat (and can get wrong):
//
// c.Mu.Lock()
// e, ok := c.Items[key]
// if ok && c.IsExpired(e, time.Now()) {
// delete(c.Items, key)
// ok = false
// }
// c.Mu.Unlock()// Package cache is a deep module: two methods, and everything else is hidden.
package cache
import (
"sync"
"time"
)
type entry struct {
value []byte
expiresAt time.Time
}
// Cache is safe for concurrent use. Locking, expiry, eviction and the clock are private decisions.
type Cache struct {
mu sync.Mutex
items map[string]entry
order []string // insertion order, used for eviction
max int
nowFunc func() time.Time
}
// New returns a cache that holds at most maxEntries values.
func New(maxEntries int) *Cache {
return &Cache{items: make(map[string]entry), max: maxEntries, nowFunc: time.Now}
}
// Get returns the value and true if it exists and has not expired.
func (c *Cache) Get(key string) ([]byte, bool) {
c.mu.Lock()
defer c.mu.Unlock()
e, ok := c.items[key]
if !ok {
return nil, false
}
if c.nowFunc().After(e.expiresAt) {
delete(c.items, key)
return nil, false
}
return e.value, true
}
// Set stores a value for ttl. When the cache is full the oldest key is evicted.
func (c *Cache) Set(key string, value []byte, ttl time.Duration) {
c.mu.Lock()
defer c.mu.Unlock()
if _, exists := c.items[key]; !exists {
c.order = append(c.order, key)
}
c.items[key] = entry{value: value, expiresAt: c.nowFunc().Add(ttl)}
for len(c.items) > c.max && len(c.order) > 0 {
oldest := c.order[0]
c.order = c.order[1:]
delete(c.items, oldest)
}
}The after version can switch to LRU, shard the map or add metrics without any caller noticing; the before version cannot change its field names.
Interfaces at the consumer side
Before: orders imports the vendor package and builds the client itself.
// Package orders (before) imports the concrete provider and builds it itself.
package orders
import (
"context"
"os"
"academy/design-quality-principles/consumeriface/stripepay"
)
// Service is tied to one vendor, one constructor and one environment variable.
type Service struct{}
// Checkout cannot be tested without the real provider package and its configuration.
func (Service) Checkout(ctx context.Context, customerID string, cents int64) (string, error) {
client := stripepay.New(os.Getenv("STRIPE_KEY"))
return client.Charge(ctx, customerID, cents)
}After: orders declares the one method it needs; stripepay returns a concrete *Client and knows nothing about orders; main wires them.
// Package orders (after) owns the interface it needs: one method, in its own words.
package orders
import (
"context"
"errors"
)
// Payments is declared by the consumer. Any type with this method satisfies it implicitly.
type Payments interface {
Charge(ctx context.Context, customerID string, cents int64) (string, error)
}
// ErrEmptyCart is part of this package's contract.
var ErrEmptyCart = errors.New("orders: cart is empty")
// Service depends on the small interface, not on a vendor package.
type Service struct {
payments Payments
}
// NewService receives its dependency; the composition root decides which one.
func NewService(p Payments) *Service { return &Service{payments: p} }
// Checkout charges the cart total.
func (s *Service) Checkout(ctx context.Context, customerID string, cents int64) (string, error) {
if cents == 0 {
return "", ErrEmptyCart
}
return s.payments.Charge(ctx, customerID, cents)
}// Package stripepay is a provider. It returns a concrete type and defines no interface.
package stripepay
import (
"context"
"fmt"
"net/http"
"time"
)
// Client talks to a payment provider over HTTP.
type Client struct {
apiKey string
http *http.Client
}
// New returns a concrete client (Go Code Review Comments: return concrete types).
func New(apiKey string) *Client {
return &Client{apiKey: apiKey, http: &http.Client{Timeout: 5 * time.Second}}
}
// Charge charges a customer and returns the provider's charge id.
func (c *Client) Charge(ctx context.Context, customerID string, cents int64) (string, error) {
if cents <= 0 {
return "", fmt.Errorf("stripepay: amount must be positive, got %d", cents)
}
// A real client would POST to the provider here using c.http and c.apiKey.
return fmt.Sprintf("ch_%s_%d", customerID, cents), nil
}
// Refund is used by another consumer; orders never needs to know it exists.
func (c *Client) Refund(ctx context.Context, chargeID string) error { return nil }// Command cmd is the composition root: the only place that knows both packages.
package main
import (
"context"
"fmt"
"log"
"academy/design-quality-principles/consumeriface/orders"
"academy/design-quality-principles/consumeriface/stripepay"
)
type fakePayments struct{}
func (fakePayments) Charge(ctx context.Context, customerID string, cents int64) (string, error) {
return "fake_charge", nil
}
func main() {
prod := orders.NewService(stripepay.New("sk_test_example"))
id, err := prod.Checkout(context.Background(), "cus_42", 1999)
if err != nil {
log.Fatal(err)
}
fmt.Println("provider:", id)
test := orders.NewService(fakePayments{})
id, _ = test.Checkout(context.Background(), "cus_42", 1999)
fmt.Println("fake:", id)
}Connascence: position, meaning, execution order
// Package user (before) shows connascence of position, meaning and execution order.
package user
import (
"errors"
"fmt"
)
// User holds an int role: 0 = member, 1 = manager, 2 = admin (connascence of meaning).
type User struct {
Name, Email string
Active bool
Role int
}
// New has five positional parameters; two bools and two strings can be swapped silently
// (connascence of position).
func New(name, email string, active, verified bool, role int) User {
_ = verified
return User{Name: name, Email: email, Active: active, Role: role}
}
// IsAdmin repeats the magic number. Every caller must agree that 2 means admin.
func IsAdmin(u User) bool { return u.Role == 2 }
// Mailer must be Init-ed before Send (connascence of execution order, temporal coupling).
type Mailer struct {
host string
ready bool
}
// Init must be called first.
func (m *Mailer) Init(host string) { m.host, m.ready = host, true }
// Send fails at runtime if the caller forgot Init.
func (m *Mailer) Send(to, body string) error {
if !m.ready {
return errors.New("mailer: Init not called")
}
fmt.Printf("smtp %s -> %s: %s\n", m.host, to, body)
return nil
}// Package user (after) turns strong connascence into weak connascence of name and type.
package user
import (
"errors"
"fmt"
)
// Role is a named type; the compiler checks it (connascence of type).
type Role int
// Named constants replace magic numbers (connascence of meaning becomes connascence of name).
const (
Member Role = iota
Manager
Admin
)
// User is built from named fields.
type User struct {
Name, Email string
Active bool
Verified bool
Role Role
}
// IsAdmin compares against a name, not a number.
func (u User) IsAdmin() bool { return u.Role == Admin }
// Example call site: every field is named, order does not matter.
var Example = User{Name: "Sara", Email: "sara@example.com", Active: true, Role: Admin}
// Mailer cannot exist in a half-initialised state.
type Mailer struct {
host string
}
// NewMailer is the only way to build a Mailer, so "Init before Send" cannot be forgotten.
func NewMailer(host string) (*Mailer, error) {
if host == "" {
return nil, errors.New("mailer: host required")
}
return &Mailer{host: host}, nil
}
// Send needs no readiness check.
func (m *Mailer) Send(to, body string) error {
fmt.Printf("smtp %s -> %s: %s\n", m.host, to, body)
return nil
}Separation of concerns: middleware
// Package handler (before) tangles four concerns in one function:
// authentication, logging, timing and the business rule.
package handler
import (
"encoding/json"
"log"
"net/http"
"time"
)
// Price handles GET /price?qty=N.
func Price(w http.ResponseWriter, r *http.Request) {
start := time.Now()
if r.Header.Get("Authorization") != "Bearer secret-token" {
log.Printf("denied %s %s", r.Method, r.URL.Path)
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
qty := 1
if r.URL.Query().Get("qty") == "10" {
qty = 10
}
total := qty * 499
if qty >= 10 {
total = total * 90 / 100
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]int{"total_cents": total})
log.Printf("%s %s %s", r.Method, r.URL.Path, time.Since(start))
}// Package handler (after) separates concerns: the rule, the HTTP adapter,
// and cross-cutting middleware are three different pieces.
package handler
import (
"encoding/json"
"log/slog"
"net/http"
"strconv"
"time"
)
// TotalCents is the business rule: no HTTP, no logging, trivially testable.
func TotalCents(qty int) int {
total := qty * 499
if qty >= 10 {
total = total * 90 / 100
}
return total
}
// Price is the HTTP adapter: decode, call the rule, encode.
func Price(w http.ResponseWriter, r *http.Request) {
qty, err := strconv.Atoi(r.URL.Query().Get("qty"))
if err != nil || qty < 1 {
qty = 1
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]int{"total_cents": TotalCents(qty)})
}
// RequireToken is a cross-cutting concern applied to any handler.
func RequireToken(token string, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") != "Bearer "+token {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
})
}
// Logging is another cross-cutting concern.
func Logging(log *slog.Logger, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
next.ServeHTTP(w, r)
log.Info("request", "method", r.Method, "path", r.URL.Path, "duration", time.Since(start))
})
}
// Routes composes the pieces; the order of wrapping is the only place they meet.
func Routes(log *slog.Logger, token string) http.Handler {
mux := http.NewServeMux()
mux.Handle("GET /price", RequireToken(token, http.HandlerFunc(Price)))
return Logging(log, mux)
}The Go angle
Go builds several of these principles into the toolchain. Unexported identifiers are encapsulation; the package is the unit of information hiding; internal/ makes a package importable only from its parent tree; import cycles are a compile error, so two packages that need each other must find the real owner of the shared concept. Interfaces are satisfied implicitly, which is what makes consumer-side interfaces possible: the consumer can declare a one-method interface that a third-party type already satisfies. The Go proverbs say "The bigger the interface, the weaker the abstraction" and "A little copying is better than a little dependency": both are coupling rules. io.Reader and io.Writer are the standard library's textbook deep interfaces: one method each, implemented by files, sockets, buffers, gzip streams and HTTP bodies.
shop/
cmd/api/main.go # composition root: the only file with Ce to everything
internal/
orders/ # core: declares Payments, Inventory interfaces it needs
payments/stripe/ # adapter: returns *Client, imports nothing from orders
inventory/postgres/ # adapter
httpapi/ # transport + middleware (cross-cutting concerns)
.go-arch-lint.yml # forbids orders -> payments/*, inventory/*Laravel
Coupling: before and after
The controller reads billing's private table, reads global config deep inside formatting, and switches output with boolean flags.
<?php
// app/Http/Controllers/OrderReportController.php
// Common coupling (config + another module's table), stamp coupling (whole model),
// control coupling (a format flag) in one controller.
namespace App\Http\Controllers;
use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class OrderReportController extends Controller
{
public function __invoke(Request $request, Order $order)
{
// Reaches into the billing module's private table (content-like coupling).
$paid = DB::table('billing_payments')->where('order_id', $order->id)->sum('amount_cents');
return response(
$this->render($order, $paid, $request->boolean('csv'), $request->boolean('notes')),
);
}
// The flags decide which branch runs: control coupling.
private function render(Order $order, int $paid, bool $csv, bool $notes): string
{
$currency = config('shop.currency'); // global, read anywhere (common coupling)
if ($csv) {
return $notes
? "{$order->id},{$paid},{$currency},\"{$order->notes}\"\n"
: "{$order->id},{$paid},{$currency}\n";
}
return sprintf('Order %d: %.2f %s', $order->id, $paid / 100, $currency);
}
}After: billing publishes a PaymentTotals contract and binds it in its own service provider; reporting uses a small OrderSummary value; formatting is two classes; config is read once at the edge with giveConfig (a documented Laravel 13 container feature).
<?php
// app/Modules/Billing/Contracts/PaymentTotals.php: the billing module's published contract.
namespace App\Modules\Billing\Contracts;
interface PaymentTotals
{
public function paidCents(int $orderId): int;
}
// app/Modules/Billing/Internal/EloquentPaymentTotals.php: only billing touches its own table.
namespace App\Modules\Billing\Internal;
use App\Modules\Billing\Contracts\PaymentTotals;
use Illuminate\Support\Facades\DB;
final class EloquentPaymentTotals implements PaymentTotals
{
public function paidCents(int $orderId): int
{
return (int) DB::table('billing_payments')->where('order_id', $orderId)->sum('amount_cents');
}
}
// app/Modules/Reporting/OrderSummary.php: the smallest data the formatters need (data coupling).
namespace App\Modules\Reporting;
final readonly class OrderSummary
{
public function __construct(
public int $orderId,
public int $paidCents,
public string $currency,
) {}
}
// app/Modules/Reporting/Formatters.php: two named functions instead of a boolean flag.
namespace App\Modules\Reporting;
final class CsvOrderFormatter
{
public function format(OrderSummary $s): string
{
return "{$s->orderId},{$s->paidCents},{$s->currency}\n";
}
}
final class TextOrderFormatter
{
public function format(OrderSummary $s): string
{
return sprintf('Order %d: %.2f %s', $s->orderId, $s->paidCents / 100, $s->currency);
}
}
// app/Http/Controllers/OrderReportController.php: depends on a contract and a value.
namespace App\Http\Controllers;
use App\Models\Order;
use App\Modules\Billing\Contracts\PaymentTotals;
use App\Modules\Reporting\CsvOrderFormatter;
use App\Modules\Reporting\OrderSummary;
class OrderReportController extends Controller
{
public function __construct(private PaymentTotals $payments, private string $currency) {}
public function csv(Order $order, CsvOrderFormatter $formatter)
{
$summary = new OrderSummary($order->id, $this->payments->paidCents($order->id), $this->currency);
return response($formatter->format($summary))->header('Content-Type', 'text/csv');
}
}
// app/Modules/Billing/BillingServiceProvider.php: the only place that knows the implementation.
namespace App\Modules\Billing;
use App\Http\Controllers\OrderReportController;
use App\Modules\Billing\Contracts\PaymentTotals;
use App\Modules\Billing\Internal\EloquentPaymentTotals;
use Illuminate\Support\ServiceProvider;
final class BillingServiceProvider extends ServiceProvider
{
public function register(): void
{
$this->app->bind(PaymentTotals::class, EloquentPaymentTotals::class);
// Config is read once, at the edge, and passed in as a plain value.
$this->app->when(OrderReportController::class)
->needs('$currency')
->giveConfig('shop.currency');
}
}Deep module: CurrencyConverter
<?php
// app/Services/RatesClient.php: a shallow wrapper. One method per HTTP call,
// so every caller still has to know caching, retries, the URL and the JSON shape.
namespace App\Services;
use Illuminate\Support\Facades\Http;
class RatesClient
{
public function fetch(string $base): array
{
return Http::get("https://rates.example.com/latest?base={$base}")->json();
}
}
// app/Http/Controllers/CheckoutController.php: one of many callers repeating the same knowledge.
namespace App\Http\Controllers;
use App\Services\RatesClient;
use Illuminate\Support\Facades\Cache;
class CheckoutController extends Controller
{
public function total(RatesClient $client, int $cents, string $to)
{
$rates = Cache::remember('rates:EUR', 3600, fn () => $client->fetch('EUR'));
$rate = $rates['rates'][$to] ?? throw new \RuntimeException("no rate for {$to}");
return ['cents' => (int) round($cents * $rate), 'currency' => $to];
}
}<?php
// app/Modules/Currency/CurrencyConverter.php: a deep module. One method in, everything else hidden:
// the provider URL, the JSON shape, caching, retries, timeouts and rounding.
namespace App\Modules\Currency;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
final readonly class Money
{
public function __construct(public int $cents, public string $currency) {}
}
final class UnknownCurrency extends \DomainException {}
final class CurrencyConverter
{
private const BASE = 'EUR';
private const TTL_SECONDS = 3600;
public function convert(Money $amount, string $to): Money
{
if ($amount->currency === $to) {
return $amount;
}
$rates = $this->rates();
$from = $rates[$amount->currency] ?? throw new UnknownCurrency($amount->currency);
$target = $rates[$to] ?? throw new UnknownCurrency($to);
return new Money((int) round($amount->cents / $from * $target), $to);
}
/** @return array<string, float> rates relative to BASE, including BASE itself */
private function rates(): array
{
return Cache::remember('currency:rates:'.self::BASE, self::TTL_SECONDS, function (): array {
$json = Http::retry(3, 200)
->timeout(5)
->get('https://rates.example.com/latest', ['base' => self::BASE])
->throw()
->json();
return [self::BASE => 1.0] + $json['rates'];
});
}
}
// app/Http/Controllers/CheckoutController.php: the caller knows one method and one value type.
namespace App\Http\Controllers;
use App\Modules\Currency\CurrencyConverter;
use App\Modules\Currency\Money;
class CheckoutController extends Controller
{
public function total(CurrencyConverter $converter, int $cents, string $to)
{
$total = $converter->convert(new Money($cents, 'EUR'), $to);
return ['cents' => $total->cents, 'currency' => $total->currency];
}
}convert(Money, string): Money hides the provider URL, the JSON shape, Cache::remember, Http::retry, the timeout and the cross-rate arithmetic. Swapping the provider or the cache store edits one file.
Events: removing temporal coupling inside the app
Laravel's events docs: "Events serve as a great way to decouple various aspects of your application, since a single event can have multiple listeners that do not depend on each other."
<?php
// app/Actions/PlaceOrder.php: the use case knows every reaction to an order.
// Adding "notify the warehouse" means editing, retesting and redeploying this class.
namespace App\Actions;
use App\Mail\OrderConfirmation;
use App\Models\Order;
use App\Services\Analytics;
use App\Services\SlackNotifier;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
class PlaceOrder
{
public function __construct(private SlackNotifier $slack, private Analytics $analytics) {}
public function handle(array $data): Order
{
$order = DB::transaction(fn () => Order::create($data));
Mail::to($order->email)->send(new OrderConfirmation($order)); // slow SMTP in the request
$this->slack->post("#sales", "New order {$order->id}"); // Slack down = checkout down
$this->analytics->track('order_placed', ['id' => $order->id]);
return $order;
}
}<?php
// app/Events/OrderPlaced.php: a fact, published after the transaction commits.
namespace App\Events;
use App\Models\Order;
use Illuminate\Contracts\Events\ShouldDispatchAfterCommit;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class OrderPlaced implements ShouldDispatchAfterCommit
{
use Dispatchable, SerializesModels;
public function __construct(public Order $order) {}
}
// app/Actions/PlaceOrder.php: the use case knows only its own job.
namespace App\Actions;
use App\Events\OrderPlaced;
use App\Models\Order;
use Illuminate\Support\Facades\DB;
class PlaceOrder
{
public function handle(array $data): Order
{
return DB::transaction(function () use ($data) {
$order = Order::create($data);
OrderPlaced::dispatch($order);
return $order;
});
}
}
// app/Listeners/SendOrderConfirmation.php: queued, retried, discovered automatically
// because it lives in app/Listeners and type-hints the event in handle().
namespace App\Listeners;
use App\Events\OrderPlaced;
use App\Mail\OrderConfirmation;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Mail;
class SendOrderConfirmation implements ShouldQueue
{
public function handle(OrderPlaced $event): void
{
Mail::to($event->order->email)->send(new OrderConfirmation($event->order));
}
}
// app/Listeners/PostOrderToSlack.php: a Slack outage now delays a message, not a checkout.
namespace App\Listeners;
use App\Events\OrderPlaced;
use App\Services\SlackNotifier;
use Illuminate\Contracts\Queue\ShouldQueue;
class PostOrderToSlack implements ShouldQueue
{
public function __construct(private SlackNotifier $slack) {}
public function handle(OrderPlaced $event): void
{
$this->slack->post('#sales', "New order {$event->order->id}");
}
}ShouldDispatchAfterCommit makes the event fire only after the transaction commits; ShouldQueue listeners run on a worker, so a Slack outage no longer fails checkout. Listeners in app/Listeners with a typed handle method are registered by event discovery.
Separation of concerns: middleware, rule, adapter
<?php
// app/Http/Middleware/EnsureApiToken.php: authentication is a cross-cutting concern.
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class EnsureApiToken
{
public function handle(Request $request, Closure $next): Response
{
if ($request->bearerToken() !== config('services.pricing.token')) {
abort(401);
}
return $next($request);
}
}
// app/Modules/Pricing/QuantityDiscount.php: the business rule. No HTTP, no logging.
namespace App\Modules\Pricing;
final class QuantityDiscount
{
public function totalCents(int $qty, int $unitCents = 499): int
{
$total = $qty * $unitCents;
return $qty >= 10 ? intdiv($total * 90, 100) : $total;
}
}
// app/Http/Controllers/PriceController.php: the HTTP adapter.
namespace App\Http\Controllers;
use App\Modules\Pricing\QuantityDiscount;
use Illuminate\Http\Request;
class PriceController extends Controller
{
public function __invoke(Request $request, QuantityDiscount $pricing)
{
$qty = max(1, $request->integer('qty', 1));
return ['total_cents' => $pricing->totalCents($qty)];
}
}
// routes/api.php: concerns meet only where they are composed.
// Route::get('/price', PriceController::class)->middleware(EnsureApiToken::class);The Laravel angle
| Laravel feature | Design-quality role |
|---|---|
Contracts (Illuminate\Contracts\*) and your own interfaces | Interfaces as contracts; depend on them, bind implementations |
| Service providers | Composition root per module; the only place that knows implementations |
Contextual binding (when()->needs()->give(), giveConfig) | Removes common coupling to config() inside logic |
| Events + queued listeners | Removes temporal coupling and control coupling between reactions |
| Middleware | Cross-cutting concerns (auth, logging, throttling) |
| Form Requests, Policies | Validation and authorization as separate concerns |
Module folders (app/Modules/*) or local Composer packages | Information hiding at module level |
deptrac / Pest arch() | Enforce module boundaries in CI |
| Facades | Convenient, but a static call is a hidden dependency: inject contracts in domain code; Laravel's docs compare the two in "Contracts vs. Facades" |
Solving the classic problems
| Problem | Solution | How | Advantage | Cost / limitation |
|---|---|---|---|---|
Global state (var DB, config() in logic) | Explicit dependencies | Constructor parameters; read config at the edge | Testable, visible | Longer constructors |
| Flag arguments | Split function | One named function per behaviour | No invalid combinations | More functions |
| Whole-record parameters | Narrow types | Pass slices, IDs, DTOs, value objects | Changes to unrelated fields do not ripple | Mapping code |
| Shallow wrappers / pass-through | Merge and deepen | Pull caller code into the module | Smaller total interface | Bigger module |
utils / helpers | Dissolve | Move each function to its user or a named package | Functional cohesion | More packages |
| Reaching into another module's tables | Published contract | Interface, view or API owned by the module | Owner can change schema | One more indirection |
| Magic numbers and positional args | Named types | Enums, constants, options structs | Compiler helps | Slightly more code |
| Required call order | Constructors, state types | Return ready objects; typestate | Misuse impossible | Less flexible setup |
| Synchronous side effects | Events | Dispatch fact; queued listeners | Failure isolation | Eventual consistency |
| Inconsistent conventions | Conceptual integrity | Style guide, ADRs, lint rules, shared middleware | Predictable system | Requires an owner |
Shared table between modules
When another module must read your data and you cannot add an API yet, publish a view as the contract and keep the table private. The view is the interface; the table is the hidden decision.
-- PostgreSQL: billing owns its tables; reporting may read only the published view.
CREATE SCHEMA billing;
CREATE TABLE billing.payments (
id BIGSERIAL PRIMARY KEY,
order_id BIGINT NOT NULL,
amount_cents BIGINT NOT NULL,
provider TEXT NOT NULL,
raw_response JSONB
);
CREATE VIEW billing.order_paid_v1 AS
SELECT order_id, SUM(amount_cents) AS paid_cents
FROM billing.payments GROUP BY order_id;
CREATE ROLE reporting_app LOGIN;
GRANT USAGE ON SCHEMA billing TO reporting_app;
GRANT SELECT ON billing.order_paid_v1 TO reporting_app; -- not on billing.payments
-- billing can now split payments into two tables; it only has to keep order_paid_v1 stable.Chatty calls between modules
Fowler's Microservices article: "A naive conversion from in-memory method calls to RPC leads to chatty communications which don't perform well. Instead you need to replace the fine-grained communication with a coarser-grained approach." Replace getPrice(sku) in a loop with quote(cart); replace three calls (stock, price, customer) with one call to an owner that has the data, or with local read models fed by events.
Temporal coupling to slow or flaky dependencies
If the caller does not need the answer to respond, publish an event (in-process: Laravel events with queued listeners; across services: outbox + broker). If it does need the answer, add a timeout, a circuit breaker and a fallback, and accept that the coupling remains.
Choosing
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| A function has a boolean that selects behaviour | Split into two named functions | Keep shared steps private | Control coupling removed |
| A module exposes its storage or lock | Deepen it | Hide behind Get/Set-style API | Information hiding |
| Two modules share one table | Single owner + view or API | Schema per module, grants | Common coupling removed |
| A class wraps another and forwards every call | Inline it | Unless it adds a different abstraction | Shallow pass-through |
A utils package grows | Dissolve it | Move Function | Coincidental cohesion |
| Interface used only for mocking, defined by implementer | Move to consumer, shrink it | Go Code Review Comments rule | Consumer owns its contract |
| A side effect may fail independently | Event + queued listener | ShouldDispatchAfterCommit | Temporal coupling removed |
| A sync call chain spans 3+ services | Coarser API or async | Read models, outbox | Availability multiplies |
| Strong connascence inside one function | Leave it | Keep it local | Locality makes it cheap |
| Strong connascence across services | Replace with name/type contract | Schema registry, versioned events | Degree and distance are high |
| Many teams, inconsistent APIs | Conceptual integrity owner | API style guide, ADRs | Brooks: few minds for the architecture |
| Hot loop, performance critical | Accept some coupling | Measure first | Indirection has a cost |
In architecture: from a single process to a distributed system
The same five properties apply at every scale; what changes is the price of getting them wrong. Inside one process, a bad dependency costs a refactoring. Across services, it costs a coordinated deploy, an outage chain or a data migration.
The picture shows the three most common service-level couplings: a shared database (common coupling), a chatty synchronous chain (temporal coupling, availability multiplies), and the fix on the right: each service owns its data and publishes events, leaving only data coupling on a versioned contract.
Monolith: one process, one database
How it shows up: packages and classes. Coupling is cheap to create (any class can call any other) and cheap to fix (the compiler and IDE find every caller).
Simplest correct usage: framework slots for concerns (middleware, form requests, actions, listeners), no globals in domain code, deep modules for the hard parts (money, tax, rates, search).
Example (simple): a blog: PostController → PublishPost action → PostPublished event → NotifySubscribers queued listener. The controller does not know mail exists.
Example (complex): a shop where OrderService called pricing, stock, invoice PDF, Slack and analytics in sequence. Split into a deep Pricing module, an OrderPlaced event with queued listeners, and a CurrencyConverter that hides the rates provider.
Modular monolith and multiple databases
How it shows up: each module (one team, one business capability) has a public contract and private internals, including private tables. This is information hiding with enforcement.
Rules: modules talk through contracts or in-process events; no module reads another's tables (use views or APIs, as in the SQL above); boundaries are tested by deptrac or go-arch-lint in CI. See Modular Monolith.
Example: app/Modules/{Catalog,Ordering,Billing} each with a service provider, a Contracts folder and an Internal folder; deptrac forbids Ordering → Billing\Internal.
Microservices: coupling with a network in the middle
What survives: every property. What changes: each form of coupling now has a runtime cost.
| In-process coupling | Service-level equivalent | Cost | Fix |
|---|---|---|---|
| Content | Service reads another's database | Schema change breaks a team you do not know | Database per service; data ownership |
| Common | Shared database or shared cache keys | microservices.io: "Development time coupling" and "Runtime coupling" | One owner per table and key prefix |
| External | Unversioned JSON both sides hand-parse | Silent breakage | Schema registry, contract tests |
| Control | ?mode=fast style flags on APIs | Callers encode the callee's logic | Separate endpoints |
| Stamp | Returning the whole customer for one field | Bandwidth, every change ripples | Purpose-specific endpoints, GraphQL field selection |
| Temporal | Synchronous call chain | Availability multiplies, latency adds | Async events, outbox, local read models |
| Chatty fine-grained calls | N calls per request | Latency × N | Coarser APIs |
| Change coupling | Services that always deploy together | Distributed monolith | Re-draw boundaries (Service Boundaries) |
Request: place order with 5 lines
1 chatty: orders -> price x5, stock x5, customer x1 11 calls, all must be up, p99 adds up
2 coarse: orders -> pricing.quote(cart), stock.reserve(cart) 2 calls
3 async: orders writes order + outbox(OrderPlaced) in one tx, returns 202
4 billing and shipping consume OrderPlaced when they are ready
5 only shared thing: the OrderPlaced v1 schema (data coupling on a contract)Example: checkout publishes OrderPlaced through an outbox; billing and shipping subscribe. Adding a loyalty service is a new subscriber, not a change to checkout. See Event-Driven Architecture and Service Communication.
Distributed data: replicas, caches and shared schemas
Where it breaks: connascence of value and identity become distributed. A cached price and the database price must agree; two services keeping their own copy of a customer address must converge. Replica lag turns "read after write" into timing connascence.
Countermeasures: one source of truth per fact; copies are derived and labelled as such (read models fed by events or CDC); TTLs and versions on cached values; idempotent consumers so redelivery does not create identity problems.
Scaling path: 1×, 10×, 100×
| Scale | Structure | Design-quality practice |
|---|---|---|
| 1× (one team) | Monolith, folders by feature | No globals in logic, deep modules for hard parts, gocyclo/phpmetrics in CI |
| 10× (several teams) | Modular monolith | Contracts per module, schema per module, deptrac/go-arch-lint, API style guide |
| 100× (many teams) | Services per capability | Database per service, versioned event contracts, async by default, platform "paved road" for cross-cutting concerns, design authority for conceptual integrity |
Lab: measure, refactor, measure again
Everything runs offline from the snippet module.
Setup.
cd docs/snippets/design/design-quality-principles/go
gofmt -l . && go vet ./... # no output, then nothing: cleanStep 1: complexity and fan-out of the coupling example. The metrics command applies gocyclo's rules with go/ast and lists each package's imports.
// Command metrics prints, for every Go package under a directory, the cyclomatic
// complexity of each function (gocyclo rules) and the package's imports (fan-out).
//
// go run ./metrics ./coupling
package main
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
"io/fs"
"os"
"path/filepath"
"sort"
"strings"
)
// complexity follows gocyclo: 1 + if, for, range, non-default case/comm clause, && and ||.
func complexity(fn *ast.FuncDecl) int {
c := 1
ast.Inspect(fn, func(n ast.Node) bool {
switch x := n.(type) {
case *ast.IfStmt, *ast.ForStmt, *ast.RangeStmt:
c++
case *ast.CaseClause:
if x.List != nil {
c++
}
case *ast.CommClause:
if x.Comm != nil {
c++
}
case *ast.BinaryExpr:
if x.Op == token.LAND || x.Op == token.LOR {
c++
}
}
return true
})
return c
}
func main() {
root := "."
if len(os.Args) > 1 {
root = os.Args[1]
}
imports := map[string]map[string]bool{}
fset := token.NewFileSet()
err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
if err != nil || d.IsDir() || !strings.HasSuffix(path, ".go") {
return err
}
f, err := parser.ParseFile(fset, path, nil, 0)
if err != nil {
return err
}
dir := filepath.Dir(path)
if imports[dir] == nil {
imports[dir] = map[string]bool{}
}
for _, imp := range f.Imports {
imports[dir][strings.Trim(imp.Path.Value, `"`)] = true
}
for _, decl := range f.Decls {
if fn, ok := decl.(*ast.FuncDecl); ok {
fmt.Printf("%-28s %-14s cyclo=%d\n", dir, fn.Name.Name, complexity(fn))
}
}
return nil
})
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
dirs := make([]string, 0, len(imports))
for d := range imports {
dirs = append(dirs, d)
}
sort.Strings(dirs)
for _, d := range dirs {
list := make([]string, 0, len(imports[d]))
for p := range imports[d] {
list = append(list, p)
}
sort.Strings(list)
fmt.Printf("%-28s fan-out=%d %s\n", d, len(list), strings.Join(list, " "))
}
}go run ./metrics ./coupling
# coupling/before Render cyclo=5
# coupling/before Total cyclo=2
# coupling/after Total cyclo=2
# coupling/after CSV cyclo=1
# coupling/after Text cyclo=1Render scores 5 because of two flags and one &&; the two named formatters score 1 each.
Step 2: separation of concerns.
go run ./metrics ./soc
# soc/before Price cyclo=4
# soc/after TotalCents cyclo=2 (the rule: unit-testable without HTTP)
# soc/after Price cyclo=3 (the adapter)
# soc/after RequireToken cyclo=2 (cross-cutting, reused by every route)The total did not go down much; what changed is that each function now has one reason to change, and the discount rule has no net/http in its path.
Step 3: afferent and efferent coupling.
go list -f '{{.ImportPath}}: {{join .Imports " "}}' ./consumeriface/...
# .../consumeriface/before: .../consumeriface/stripepay context os
# .../consumeriface/cmd: .../consumeriface/orders .../consumeriface/stripepay context fmt log
# .../consumeriface/orders: context errors
# .../consumeriface/stripepay: context fmt net/http timeCompute I = Ce / (Ca + Ce) counting only project packages: orders (after) has Ce = 0, so I = 0; cmd has Ce = 2, Ca = 0, so I = 1; orders (before) has Ce = 1 (stripepay), I = 1. The after design points every dependency toward the stable core.
Step 4: break a boundary on purpose. Add import _ "academy/design-quality-principles/consumeriface/stripepay" to consumeriface/orders/orders.go. Expected: it still compiles (Go has no layer rules) but go list now shows Ce = 1 for orders. This is why you add go-arch-lint; with the config from Architecture rules and orders forbidden from depending on adapters, go-arch-lint check fails. Remove the import.
Step 5: connascence. In connascence/before, swap the two booleans in a call to New (New("a", "b", false, true, 2)). Expected: compiles, wrong user. Try the same with after.User{...} named fields: order no longer matters, and Role: 2 must be written Role: Admin to read well.
Step 6 (Laravel). In a Laravel 13 app, copy CouplingAfter.php classes into their paths and deptrac.yaml to the root, then add DB::table('billing_payments') to the controller. Expected: vendor/bin/deptrac analyse passes (the facade is not in a layer) but a Pest arch() rule expect('App\Http')->not->toUse('Illuminate\Support\Facades\DB') fails. Then run phpmetrics --report-html=report ./app and compare lcom and instability for the old and new controller.
| Measurement | Before | After |
|---|---|---|
| Max cyclomatic in report formatting | 5 (Render) | 1 (CSV, Text) |
Globals in report | 2 (DB, Currency) | 0 |
Project packages orders imports | 1 (stripepay) | 0 |
Instability of orders | 1.0 | 0.0 |
| Cache methods a caller must know | 4 names + protocol | 2 (Get, Set) |
| Functions that change when the discount changes | Price (also holds auth, logging) | TotalCents only |
Common misconceptions
| Belief | Reality |
|---|---|
| Low coupling means zero dependencies | Modules must talk; aim for few, weak, one-directional dependencies (Fowler 2001) |
| Small classes are always better | Many shallow classes raise total interface size ("classitis", Ousterhout) |
| Private fields equal information hiding | Getters/setters for everything leak the design; hiding is about decisions |
| An interface decouples by itself | Flags, whole records and call-order rules still couple through an interface |
| Interfaces belong next to the implementation | In Go they belong with the consumer (Go Code Review Comments) |
| Instability is bad | Adapters should be unstable; stable code should not depend on them |
| Cyclomatic complexity measures readability | It counts paths for testing; nesting and naming matter more for reading |
| LCOM tells you how to split a class | It finds field-sharing clusters, not responsibilities |
| Separation of concerns means controller/service/repository | Layers are one technical split; business concerns need separating too |
| Conceptual integrity means one person writes all the code | One mind (or a few) owns the architecture; many hands implement |
| Microservices give you low coupling | Shared databases and sync chains make a distributed monolith |
| Async messaging removes coupling | It removes temporal coupling; the message schema is still a contract |
| All duplication must be removed | Duplication implies coupling, but merging code owned by different actors couples them more (see SRP) |
Cheat sheet
| Topic | Remember |
|---|---|
| Complexity | Symptoms: change amplification, cognitive load, unknown unknowns. Causes: dependencies, obscurity |
| Essential vs accidental | Contain the essential, delete the accidental (Brooks 1986) |
| Coupling scale | Content, common, external, control, stamp, data (tightest to loosest) |
| Extra coupling forms | Temporal (order/availability), change coupling (git), pathological = content |
| Package metrics | Ca in, Ce out, I = Ce / (Ca + Ce); depend toward lower I |
| Cohesion scale | Coincidental, logical, temporal, procedural, communicational, sequential, functional |
| Information hiding | Hide decisions likely to change (Parnas 1972); encapsulation is the mechanism |
| Interfaces | Formal + informal parts; Go: declare at the consumer, return concrete types |
| Deep modules | Small interface, lots hidden; red flags: pass-through methods, classitis |
| Separation of concerns | Rule, transport, persistence apart; cross-cutting in middleware/decorators/events |
| Conceptual integrity | One set of ideas; architect role, ADRs, style guide; leave out features that do not fit |
| Connascence | Strength, degree, locality; name and type are weak, meaning/position/timing are strong |
| Metrics | McCabe limit 10; gocyclo, phpmetrics (ccn, lcom, instability) |
| Rules in CI | go-arch-lint, deptrac, Pest arch() |
| Services | No shared DB, coarse APIs, async for side effects, versioned contracts |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — What are Ousterhout's three symptoms of complexity, and what are its two causes? Important
Answer
Answer: Change amplification, cognitive load, unknown unknowns; caused by dependencies and obscurity. See Complexity.
2 — Put these in order from tightest to loosest: stamp, content, data, control, common, external. Good to know
Answer
Answer: Content, common, external, control, stamp, data. See Coupling.
3 — func Render(o *Order, asCSV bool) uses which two kinds of coupling, and how do you fix them? Important
Answer
Answer: Stamp coupling (whole *Order) and control coupling (asCSV). Pass a small Summary value and split into CSV(s) and Text(s). See Go coupling.
4 — A boot() function opens the database, warms the cache and posts to Slack. Which cohesion level is it? Important
Answer
Answer: Temporal cohesion: the parts are together only because they run at the same time. See Cohesion.
5 — A class has only private fields and a public getter and setter for each. Does it practise information hiding? Must-know
Answer
Answer: Encapsulation yes, information hiding no: the field layout is the interface. See Information hiding.
6 — In Go, where should the Payments interface used by orders be declared, and what should stripepay.New return? Must-know
Answer
Answer: In orders, the consumer; stripepay.New returns the concrete *Client. See Interfaces as contracts.
7 — What is a pass-through method and why is it a red flag? Important
Answer
Answer: A method that forwards to another with the same signature and no new abstraction; it adds interface without functionality, making the module shallow. See Deep vs shallow.
8 — Package A has Ca = 6 and Ce = 2. What is its instability, and may it depend on package B with I = 0.8? Important
Answer
Answer: I = 2 / (6 + 2) = 0.25. Depending on B (0.8) violates "depend upon packages whose I metric is lower than yours". See Instability.
9 — Order role == 2, New(a, b, true, false) and Init() before Send() by connascence form. Good to know
Answer
Answer: Meaning (static), position (static), execution order (dynamic). Fix with named constants, named fields, and a constructor. See Connascence.
10 — Two services read and write one customers table. Name the coupling and two costs microservices.io lists. Must-know
Answer
Answer: Common coupling at service level; development-time coupling (coordinate schema changes) and runtime coupling (they interfere with each other). See Microservices.
11 — How does a team lose conceptual integrity, and name two countermeasures. Important
Answer
Answer: Many authors adding features with their own conventions and no owner of the concepts. Countermeasures: an architect/design-authority role, ADRs, an API style guide enforced by middleware and lint. See Conceptual integrity.
12 — Does replacing a synchronous call with an event remove all coupling? Must-know
Answer
Answer: No. It removes temporal coupling; the event schema remains a data-coupling contract that needs versioning. See Temporal coupling.
Glossary
| Term | Meaning |
|---|---|
| Complexity | Anything in a system's structure that makes it hard to understand and modify (Ousterhout) |
| Change amplification | A simple change requires edits in many places |
| Cognitive load | How much a developer must know to make a change |
| Unknown unknowns | Required knowledge that is not visible where you make the change |
| Obscurity | Important information is not obvious |
| Essential complexity | Complexity inherent in the problem (Brooks 1986) |
| Accidental complexity | Complexity introduced by our tools and choices |
| Coupling | Strength of association created by a connection between modules |
| Content coupling | Using or modifying another module's internals; Page-Jones calls it pathological |
| Pathological coupling | Page-Jones's name for content coupling, the tightest level |
| Common coupling | Sharing global mutable data |
| External coupling | Sharing an externally imposed format, protocol or device |
| Control coupling | Passing a flag that selects the callee's behaviour |
| Stamp coupling | Passing a whole structure when only part is used |
| Data coupling | Passing only the elementary data needed |
| Temporal coupling | Dependency on order or simultaneity of execution or availability |
| Change (logical) coupling | Files that change together in version history |
| Afferent coupling (Ca) | Number of outside classes depending on a package |
| Efferent coupling (Ce) | Number of outside classes a package depends on |
| Instability (I) | Ce / (Ca + Ce), from 0 stable to 1 unstable |
| Fan-in / fan-out | Callers of a unit / units it calls |
| Cohesion (binding) | How strongly the elements of a module belong together |
| Coincidental / logical / temporal / procedural / communicational / sequential / functional cohesion | The seven cohesion levels, weakest to strongest |
| Information hiding | Hiding design decisions likely to change behind an interface (Parnas 1972) |
| Encapsulation | Language mechanisms that restrict access to a module's internals |
| Information leakage | A design decision known to more than one module |
| Temporal decomposition | Splitting code by execution order; a common cause of leakage |
| Interface | Everything a caller must know: formal signatures plus informal behaviour |
| Contract | The guarantees and obligations of an interface, including errors and ordering |
| Deep module | Small interface, much hidden functionality |
| Shallow module | Interface about as complex as its implementation |
| Pass-through method | A method that forwards a call without adding abstraction |
| Classitis | Ousterhout's name for many tiny shallow classes |
| Separation of concerns | Treating each aspect in isolation (Dijkstra 1974) |
| Cross-cutting concern | A concern that touches many modules: logging, auth, tracing, transactions |
| Tangling / scattering | Many concerns in one place / one concern in many places |
| Conceptual integrity | One coherent set of design ideas across a system (Brooks 1975) |
| Connascence | Two elements must change together to stay correct (Page-Jones) |
| Strength / degree / locality | Connascence axes: how hard to refactor, how many affected, how far apart |
| Static / dynamic connascence | Visible in source / visible only at runtime |
| Cyclomatic complexity | Number of independent paths, v = e - n + 2p (McCabe 1976) |
| LCOM | Lack of Cohesion of Methods |
| gocyclo / go-arch-lint | Go tools: cyclomatic complexity; dependency rules between components |
| phpmetrics / deptrac | PHP tools: metrics report; layer dependency rules |
| Distributed monolith | Services that must change and deploy together |
| Chatty API | Fine-grained remote calls that multiply latency and failure |
References
- D. L. Parnas, "On the Criteria To Be Used in Decomposing Systems into Modules", Communications of the ACM 15(12), 1972. PDF
- W. P. Stevens, G. J. Myers, L. L. Constantine, "Structured Design", IBM Systems Journal 13(2), 1974 (1999 reprint). PDF copy
- E. W. Dijkstra, "On the role of scientific thought" (EWD447), 1974. E.W. Dijkstra Archive (archived copy)
- F. P. Brooks, The Mythical Man-Month, Addison-Wesley, chapter 4 "Aristocracy, Democracy, and System Design". Course PDF (University of Michigan)
- F. P. Brooks, "No Silver Bullet: Essence and Accident in Software Engineering", 1986. PDF
- T. J. McCabe, "A Complexity Measure", IEEE Transactions on Software Engineering, December 1976. PDF
- J. Ousterhout, CS 190 lecture notes: The Nature of Complexity, Modular Design; book page A Philosophy of Software Design
- R. C. Martin, Design Principles and Design Patterns, 2000 (Ca, Ce, I, SDP). PDF mirror
- M. Fowler, "Reducing Coupling", IEEE Software, 2001. PDF; Design Stamina Hypothesis; J. Lewis and M. Fowler, Microservices
- connascence.io: overview, strength, locality, degree, meaning
- T. Barrett-Powell, "Coupling", ACCU 2010 (cites Page-Jones 1988 on pathological coupling). PDF
- Wikipedia (secondary): Coupling (computer programming), Connascence
- C. Richardson, Shared database pattern
- Go: Code Review Comments: Interfaces, Go Proverbs, gocyclo, go-arch-lint
- PHP: PhpMetrics metrics, deptrac, CK metrics tool
- Laravel 13: Contracts, Events, Service Container (contextual binding), Middleware