Skip to content

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 forGo to
Every principle on one screenEverything in one minute
Why any of this costs or saves moneyWhy design quality matters
Parnas, Constantine, Brooks, Dijkstra, McCabe, Ousterhout, Page-JonesWhere it comes from
Complexity and its symptomsComplexity, Essential vs accidental
The coupling scale, temporal coupling, Ca/Ce/instabilityCoupling, Temporal coupling, Afferent, efferent, instability
The cohesion scaleCohesion
Information hiding, encapsulation, interfaces, deep modulesInformation hiding, Interfaces as contracts, Deep vs shallow
Separation of concerns, cross-cutting concernsSeparation of concerns
Conceptual integrity and how teams lose itConceptual integrity
Connascence: name, type, meaning, position, algorithm, execution, timing, value, identityConnascence
Cyclomatic complexity, LCOM, fan-in/out, gocyclo, go-arch-lint, phpmetrics, deptracMechanics
Before/after codeGo, Laravel
Globals, flags, shallow wrappers, shared tables, chatty callsSolving the classic problems
Shared DB, chatty APIs, temporal coupling between servicesIn architecture
Hands-on measurementLab

Everything in one minute ​

The principles. Each row is unpacked in the concept catalogue.

PrincipleIn plain wordsSymptom when missingFirst fix
Low complexityThe system is easy to understand and changeA one-line feature takes a weekRemove dependencies and obscurity
Low couplingChanging A rarely forces changing B"I only touched X and Y broke"Pass data, not flags or globals
High cohesionEverything in a module belongs togetherutils, helpers, Manager classesMove code next to its only user
Information hidingEach module hides one decision likely to changeCallers know your table names, lock, retry policyShrink the interface
Deep modulesSmall interface, lots of hidden functionalityPass-through wrappers, classitisMerge shallow pieces, pull complexity down
Separation of concernsDifferent concerns live in different placesAuth, logging and rules in one functionMiddleware, layers, events
Conceptual integrityThe whole system reflects one set of ideasThree ways to paginate, two error formatsOne architect role, ADRs, style guide
Weak connascenceWhat must change together is named and closeMagic numbers, positional args across modulesNamed types, constructors, keep it local

The coupling scale (tightest first). Full block: Coupling.

LevelWhat is sharedTiny example
Content (pathological)Internals: code or private data of the other moduleReflection on private fields; SQL into another module's tables
CommonGlobal mutable datavar DB *sql.DB, config() read deep inside logic
ExternalAn imposed format, protocol or deviceTwo modules parse the same CSV layout
ControlA flag that picks the callee's branchRender(o, true, false)
StampA whole structure, partly usedPassing an Eloquent model to read id
DataOnly the elementary values neededTotal(lines, "EUR")

The cohesion scale (weakest first). Full block: Cohesion.

LevelWhy the parts are togetherTiny example
CoincidentalNo reasonhelpers.php
LogicalSame category, chosen by a flagExporter::export($type)
TemporalRun at the same momentboot() that does five unrelated things
ProceduralSteps of one procedure on different data"check permission, then open file"
CommunicationalWork on the same dataEvery method reads the same Order
SequentialOutput of one is input of the nextparse → validate → normalise
FunctionalAll parts serve one well-defined taskCurrencyConverter::convert

What you can measure. Full block: Mechanics.

MetricMeasuresGo toolPHP tool
Cyclomatic complexityIndependent paths through a functiongocyclo, golangci-lint (gocyclo linter)phpmetrics (ccn)
LCOMMethods that share no fieldsnone built inphpmetrics (lcom)
Fan-in / fan-outWho uses me / whom I usego list -deps, import graphphpmetrics (afferent/efferent)
Ca, Ce, Instability I = Ce / (Ca + Ce)Package stabilityimport graph scriptphpmetrics (instability)
Forbidden dependenciesArchitecture rulesgo-arch-lintdeptrac, Pest arch()
Change couplingFiles that change togethergit log analysisgit 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 commitSlightly slower first commit
Call whatever you can reachCall only published interfaces
Globals and flags are convenientDependencies are passed explicitly
Each feature adds its own styleOne style, written down
Cost grows with every changeCost grows slowly
Risk: big ball of mudRisk: 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 ​

  1. "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.
  2. "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.
  3. "Encapsulation and information hiding are the same thing." Making fields private is 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:

SymptomOusterhout's wordingWhat 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.

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

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

ExampleEssentialAccidental
VAT across 27 EU countriesRates, reverse charge, thresholdsThe rule copied into 4 services
Exchange ratesRates change; providers failEvery caller handles caching and retries itself
Order state machineAllowed transitionsStatus codes as magic integers
Distributed checkoutPartial failure is realA 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."

Coupling scale (Myers, Page-Jones; Stevens et al. 1974)Content(pathological)reads or editsanother module'sinternalsreflection onprivate fieldsCommonshared globalmutable datavar DB, config()shared tableExternalimposed format,protocol, deviceboth parse oneCSV layoutControla flag tells thecallee what to dorender(o, true)Stampwhole record,only part usedpass Order,use only idDataonly the elementaryvalues neededTotal(lines, cur)tightest (left) to loosest (right): aim for data coupling across module boundariesTemporal couplingmust happen in order or at the same time:Init() before Send(); sync call needs callee upChange (logical) couplingno call between them, yet they change togetherin git history: invisible to static tools

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.

LevelDefinitionGo exampleLaravel exampleFix
Content (pathological)One module uses or modifies the internals of anotherunsafe/reflect to set a private field; importing another team's internal by copying itDB::table('billing_payments') from the reporting moduleCall the owner's published API
CommonSeveral modules share global datavar DB *sql.DB, package-level Currencyconfig() read inside domain logic; a shared settings tablePass dependencies explicitly; read config at the edge
ExternalShared externally imposed format, protocol or deviceTwo packages hand-parse the same fixed-width fileTwo jobs build the same partner XML by handOne adapter owns the format
ControlCaller passes a flag that selects behaviourRender(o, asCSV, withNotes)export($order, 'pdf') with a match insideSplit into named functions (CSV, Text)
Stamp (data-structured)A whole structure is passed, only part usedfunc Total(o *Order) reading only LinesPassing a User model to read idPass the smallest type: []Line, int $userId, a DTO
DataOnly elementary values or small value objectsTotal(lines []Line, cur string) Moneynew 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:

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

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

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

Real 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)CaCeIVerdict
orders (consumer interface)1 (cmd)0 project packages0.0Stable core, as wanted
stripepay1 (cmd)0 project packages0.0Leaf adapter
cmd021.0Composition root: unstable by design
orders (before)01 (stripepay)1.0Core 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."

stronger cohesion7 Functionalevery part serves one task: payroll.CalculatePay and its helpers6 Sequentialoutput of one step is input of the next: parse, validate, normalise5 Communicationalparts work on the same data: all methods read one Order4 Proceduralsteps of one procedure, different data: check permission, open file3 Temporalrun at the same time: boot() opens DB, warms cache, sends ping2 Logicalsame category, picked by a flag: Exporter with CSV, PDF, XML1 Coincidentalno relation at all: helpers.php, package utils1974 scale: six levels; procedural (4) added in later texts
LevelElements are together becauseGo exampleLaravel exampleMove to fix
1 CoincidentalNo reasonpackage utils with Slugify, Retry, TaxRateapp/helpers.phpMove each function to its only user or a purposeful package
2 LogicalSame category, selected by a flagExport(kind string) with a switchExportService::run($type)One type per variant behind an interface
3 TemporalExecuted at the same timefunc boot() opens DB, warms cache, pings SlackOne AppServiceProvider::boot() doing everythingEach module registers its own startup
4 ProceduralSteps of one procedure, unrelated datacheckPermThenOpenFile()Controller method that authorizes then formats a CSVSplit by data
5 CommunicationalOperate on the same dataMethods all on one OrderModel methods on one OrderUsually fine
6 SequentialOutput of one feeds the nextparse → validate → normalisePipeline (Illuminate\Pipeline) stagesFine; watch the stage interfaces
7 FunctionalAll contribute to one taskcache.Get/SetCurrencyConverter::convertThe target
text
     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.go

Before/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 hidingEncapsulation
KindDesign principleLanguage mechanism
QuestionWhich decisions may change, and who must not know them?Which names are visible outside?
GoPackage boundary, internal/, small exported APILowercase identifiers are unexported
PHPModule boundary, contract interface, @internal + deptrac ruleprivate, protected, readonly
Fails whenInterface mirrors implementationGetters/setters for everything; reflection
text
     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 only

Real 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 partGoLaravel / PHPBetween services
SignatureMethod setInterface methods, typesOpenAPI path, protobuf message
ErrorsSentinel errors, errors.IsTyped exceptionsStatus codes, error body schema
BehaviourDoc commentPHPDocAPI docs, examples
Ordering / lifecycleConstructor returns ready valueContainer binding, constructorIdempotency 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").

Deep moduleGet, Setlockingexpiryevictionclockstorage layoutretries, caching(all hidden)small interface, lots of functionalitye.g. Unix open, read, write, lseek, closeShallow moduleMu, Items, Entry, IsExpired, New ...almost nothing hiddenevery caller repeats: lock, look up,check expiry, delete, unlockinterface cost close to implementation coste.g. pass-through wrappers, classitistop edge = interface (cost to learn)area = functionality (benefit)

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.

SignalDeepShallow
Interface vs implementation sizeMuch smallerAbout the same
Callers repeat setup or protocolNoYes
Can change implementation freelyYesNo, callers depend on it
Typical formCurrencyConverter::convert, io.Reader, net/http.Client.DoGetter/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).

text
     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 concernGoLaravel
Authenticationfunc(http.Handler) http.Handler middlewareMiddleware (auth:sanctum, custom)
AuthorizationMiddleware or explicit check in use casePolicies, Gates
Logging / tracingMiddleware, log/slog, OpenTelemetry handlersMiddleware, log context, Telescope/Pulse
TransactionsUse-case function with db.BeginTxDB::transaction in the action
ValidationDecode + validate in handler adapterForm Requests
CachingDecorator around an interfaceCache::remember inside a deep module
Side effects after a factPublish an eventEvents + 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:

CauseWhat it looks likeCountermeasure
Many authors, no owner of the conceptsThree pagination styles: ?page=, ?offset=, cursorAn architect role or design authority for the external spec
Feature-by-feature growthEach endpoint invents its own error JSONOne error format (e.g. RFC 9457 problem details), enforced in middleware
Team turnoverNew team re-solves an old problem differentlyADRs that record the decision and its reason
Framework mixingHalf the app uses Eloquent, half raw SQL with arraysA written "how we do X here" guide and lint rules
Microservices without a platformEach service has its own auth, logging, config stylePaved road / shared libraries, API style guide
Copying from the internetPatterns that fight the frameworkReview against the guide, not taste

Before/after (conceptual integrity):

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

Fix: 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 / dynamicTwo pieces must agree onExampleWeaker alternative
NameStaticA nameCalling Charge(already weakest)
TypeStaticA typeint cents vs float eurosValue types (Money)
Meaning (convention)StaticWhat a value meansrole == 2 means admin; "9999-9999-9999-9999" is a test cardNamed constants, enums
PositionStaticOrder of valuesNew(name, email, true, false, 2)Named fields, options struct
AlgorithmStaticThe same algorithmClient and server both compute an HMAC or checksumOne shared function or library
Execution (order)DynamicOrder of executionInit() before Send()Constructor returns ready object
TimingDynamicTiming of executionRace between cache write and read; timeout assumptionsSynchronisation, idempotency
ValueDynamicValues that must stay consistentTwo replicas of a price; a cached totalSingle source of truth, derive
IdentityDynamicReference the same instanceTwo services must update the same rowOne owner, IDs not object references
text
     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 visible

Rule 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 / frameworkUnit of hidingInterface mechanismBoundary enforcementMetrics and rules
GoPackage (internal/ for module-private)Implicit interfaces, declared by the consumerCompiler: unexported names, internal/, no import cyclesgocyclo, gocognit, golangci-lint, go-arch-lint, go list -deps
PHP / LaravelClass + module folder or Composer packageinterface, Laravel contracts, container bindingsprivate/readonly, deptrac layers, Pest arch() testsphpmetrics, PHPStan/Larastan, deptrac
Java / SpringPackage + JPMS moduleinterface, Spring beansPackage-private, module-info.java, ArchUnitCK (CBO, LCOM, FAN-IN/OUT), SonarQube
C# / .NETAssemblyinterface, DI containerinternal, project references, NetArchTestVisual Studio code metrics (class coupling, cyclomatic)
TypeScriptES module + packageStructural typesexports map, eslint import rules, dependency-cruiserdependency-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.

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

LCOM: 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 ​

MetricFormulaHealthy patternUnhealthy pattern
Fan-in (Ca)modules that depend on this oneHigh on small, stable modules (money, time)High on a module that changes weekly
Fan-out (Ce)modules this one depends onHigh only in composition roots (main, service providers)High in domain code
Instability ICe / (Ca + Ce)Dependencies point toward lower IStable core imports unstable adapter
Abstractness Aabstract types / all typesStable packages are abstractStable and concrete ("zone of pain")
Distance Dabs(A + I - 1)Near 0 ("main sequence")Near 1
Structural complexity (Card & Agresti, phpmetrics)fan-out squaredLowGrows 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)"):

yaml
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:
      - repository
bash
go 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.

yaml
# 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: ~
bash
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, instability

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

ToolLanguageMeasures / enforcesTypical CI gate
gocycloGoCyclomatic complexity per functiongocyclo -over 15 ./...
gocognitGoCognitive complexityvia golangci-lint
golangci-lintGoRuns gocyclo, gocognit, depguard and moregolangci-lint run
go-arch-lintGoAllowed dependencies between componentsgo-arch-lint check
phpmetricsPHPccn, lcom, Ca/Ce/instability, maintainability indexHTML report, thresholds by script
deptracPHPAllowed dependencies between layersvendor/bin/deptrac analyse
Pest arch()PHPExpectations such as "App\Modules\Billing may not be used by X"./vendor/bin/pest --filter=arch
PHPStan / LarastanPHPTypes (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).

go
// 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).

go
// 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 ​

go
// 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()
go
// 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.

go
// 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.

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

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

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

text
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
<?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
<?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
<?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
<?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
<?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
<?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
<?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 featureDesign-quality role
Contracts (Illuminate\Contracts\*) and your own interfacesInterfaces as contracts; depend on them, bind implementations
Service providersComposition root per module; the only place that knows implementations
Contextual binding (when()->needs()->give(), giveConfig)Removes common coupling to config() inside logic
Events + queued listenersRemoves temporal coupling and control coupling between reactions
MiddlewareCross-cutting concerns (auth, logging, throttling)
Form Requests, PoliciesValidation and authorization as separate concerns
Module folders (app/Modules/*) or local Composer packagesInformation hiding at module level
deptrac / Pest arch()Enforce module boundaries in CI
FacadesConvenient, 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 ​

ProblemSolutionHowAdvantageCost / limitation
Global state (var DB, config() in logic)Explicit dependenciesConstructor parameters; read config at the edgeTestable, visibleLonger constructors
Flag argumentsSplit functionOne named function per behaviourNo invalid combinationsMore functions
Whole-record parametersNarrow typesPass slices, IDs, DTOs, value objectsChanges to unrelated fields do not rippleMapping code
Shallow wrappers / pass-throughMerge and deepenPull caller code into the moduleSmaller total interfaceBigger module
utils / helpersDissolveMove each function to its user or a named packageFunctional cohesionMore packages
Reaching into another module's tablesPublished contractInterface, view or API owned by the moduleOwner can change schemaOne more indirection
Magic numbers and positional argsNamed typesEnums, constants, options structsCompiler helpsSlightly more code
Required call orderConstructors, state typesReturn ready objects; typestateMisuse impossibleLess flexible setup
Synchronous side effectsEventsDispatch fact; queued listenersFailure isolationEventual consistency
Inconsistent conventionsConceptual integrityStyle guide, ADRs, lint rules, shared middlewarePredictable systemRequires 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.

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

SituationRecommendationExtra techniqueReason
A function has a boolean that selects behaviourSplit into two named functionsKeep shared steps privateControl coupling removed
A module exposes its storage or lockDeepen itHide behind Get/Set-style APIInformation hiding
Two modules share one tableSingle owner + view or APISchema per module, grantsCommon coupling removed
A class wraps another and forwards every callInline itUnless it adds a different abstractionShallow pass-through
A utils package growsDissolve itMove FunctionCoincidental cohesion
Interface used only for mocking, defined by implementerMove to consumer, shrink itGo Code Review Comments ruleConsumer owns its contract
A side effect may fail independentlyEvent + queued listenerShouldDispatchAfterCommitTemporal coupling removed
A sync call chain spans 3+ servicesCoarser API or asyncRead models, outboxAvailability multiplies
Strong connascence inside one functionLeave itKeep it localLocality makes it cheap
Strong connascence across servicesReplace with name/type contractSchema registry, versioned eventsDegree and distance are high
Many teams, inconsistent APIsConceptual integrity ownerAPI style guide, ADRsBrooks: few minds for the architecture
Hot loop, performance criticalAccept some couplingMeasure firstIndirection 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.

Shared databaseordersbillingone schema,two writerscommon coupling:schema change needs both teamsChatty sync callsordersstockpricecustomerx N lines per requesttemporal coupling: all must be up;0.99 x 0.99 x 0.99 availabilityand latencies add upOwned data + eventsordersoutboxbrokerbillingshippingdata coupling on OrderPlaced v1;consumers may be down for a while

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 couplingService-level equivalentCostFix
ContentService reads another's databaseSchema change breaks a team you do not knowDatabase per service; data ownership
CommonShared database or shared cache keysmicroservices.io: "Development time coupling" and "Runtime coupling"One owner per table and key prefix
ExternalUnversioned JSON both sides hand-parseSilent breakageSchema registry, contract tests
Control?mode=fast style flags on APIsCallers encode the callee's logicSeparate endpoints
StampReturning the whole customer for one fieldBandwidth, every change ripplesPurpose-specific endpoints, GraphQL field selection
TemporalSynchronous call chainAvailability multiplies, latency addsAsync events, outbox, local read models
Chatty fine-grained callsN calls per requestLatency × NCoarser APIs
Change couplingServices that always deploy togetherDistributed monolithRe-draw boundaries (Service Boundaries)
text
     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× ​

ScaleStructureDesign-quality practice
1× (one team)Monolith, folders by featureNo globals in logic, deep modules for hard parts, gocyclo/phpmetrics in CI
10× (several teams)Modular monolithContracts per module, schema per module, deptrac/go-arch-lint, API style guide
100× (many teams)Services per capabilityDatabase 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.

bash
cd docs/snippets/design/design-quality-principles/go
gofmt -l . && go vet ./...      # no output, then nothing: clean

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

go
// 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, " "))
	}
}
bash
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=1

Render scores 5 because of two flags and one &&; the two named formatters score 1 each.

Step 2: separation of concerns.

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

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

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

MeasurementBeforeAfter
Max cyclomatic in report formatting5 (Render)1 (CSV, Text)
Globals in report2 (DB, Currency)0
Project packages orders imports1 (stripepay)0
Instability of orders1.00.0
Cache methods a caller must know4 names + protocol2 (Get, Set)
Functions that change when the discount changesPrice (also holds auth, logging)TotalCents only

Common misconceptions ​

BeliefReality
Low coupling means zero dependenciesModules must talk; aim for few, weak, one-directional dependencies (Fowler 2001)
Small classes are always betterMany shallow classes raise total interface size ("classitis", Ousterhout)
Private fields equal information hidingGetters/setters for everything leak the design; hiding is about decisions
An interface decouples by itselfFlags, whole records and call-order rules still couple through an interface
Interfaces belong next to the implementationIn Go they belong with the consumer (Go Code Review Comments)
Instability is badAdapters should be unstable; stable code should not depend on them
Cyclomatic complexity measures readabilityIt counts paths for testing; nesting and naming matter more for reading
LCOM tells you how to split a classIt finds field-sharing clusters, not responsibilities
Separation of concerns means controller/service/repositoryLayers are one technical split; business concerns need separating too
Conceptual integrity means one person writes all the codeOne mind (or a few) owns the architecture; many hands implement
Microservices give you low couplingShared databases and sync chains make a distributed monolith
Async messaging removes couplingIt removes temporal coupling; the message schema is still a contract
All duplication must be removedDuplication implies coupling, but merging code owned by different actors couples them more (see SRP)

Cheat sheet ​

TopicRemember
ComplexitySymptoms: change amplification, cognitive load, unknown unknowns. Causes: dependencies, obscurity
Essential vs accidentalContain the essential, delete the accidental (Brooks 1986)
Coupling scaleContent, common, external, control, stamp, data (tightest to loosest)
Extra coupling formsTemporal (order/availability), change coupling (git), pathological = content
Package metricsCa in, Ce out, I = Ce / (Ca + Ce); depend toward lower I
Cohesion scaleCoincidental, logical, temporal, procedural, communicational, sequential, functional
Information hidingHide decisions likely to change (Parnas 1972); encapsulation is the mechanism
InterfacesFormal + informal parts; Go: declare at the consumer, return concrete types
Deep modulesSmall interface, lots hidden; red flags: pass-through methods, classitis
Separation of concernsRule, transport, persistence apart; cross-cutting in middleware/decorators/events
Conceptual integrityOne set of ideas; architect role, ADRs, style guide; leave out features that do not fit
ConnascenceStrength, degree, locality; name and type are weak, meaning/position/timing are strong
MetricsMcCabe limit 10; gocyclo, phpmetrics (ccn, lcom, instability)
Rules in CIgo-arch-lint, deptrac, Pest arch()
ServicesNo shared DB, coarse APIs, async for side effects, versioned contracts

Self-check: questions & answers ​

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

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

TermMeaning
ComplexityAnything in a system's structure that makes it hard to understand and modify (Ousterhout)
Change amplificationA simple change requires edits in many places
Cognitive loadHow much a developer must know to make a change
Unknown unknownsRequired knowledge that is not visible where you make the change
ObscurityImportant information is not obvious
Essential complexityComplexity inherent in the problem (Brooks 1986)
Accidental complexityComplexity introduced by our tools and choices
CouplingStrength of association created by a connection between modules
Content couplingUsing or modifying another module's internals; Page-Jones calls it pathological
Pathological couplingPage-Jones's name for content coupling, the tightest level
Common couplingSharing global mutable data
External couplingSharing an externally imposed format, protocol or device
Control couplingPassing a flag that selects the callee's behaviour
Stamp couplingPassing a whole structure when only part is used
Data couplingPassing only the elementary data needed
Temporal couplingDependency on order or simultaneity of execution or availability
Change (logical) couplingFiles 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-outCallers of a unit / units it calls
Cohesion (binding)How strongly the elements of a module belong together
Coincidental / logical / temporal / procedural / communicational / sequential / functional cohesionThe seven cohesion levels, weakest to strongest
Information hidingHiding design decisions likely to change behind an interface (Parnas 1972)
EncapsulationLanguage mechanisms that restrict access to a module's internals
Information leakageA design decision known to more than one module
Temporal decompositionSplitting code by execution order; a common cause of leakage
InterfaceEverything a caller must know: formal signatures plus informal behaviour
ContractThe guarantees and obligations of an interface, including errors and ordering
Deep moduleSmall interface, much hidden functionality
Shallow moduleInterface about as complex as its implementation
Pass-through methodA method that forwards a call without adding abstraction
ClassitisOusterhout's name for many tiny shallow classes
Separation of concernsTreating each aspect in isolation (Dijkstra 1974)
Cross-cutting concernA concern that touches many modules: logging, auth, tracing, transactions
Tangling / scatteringMany concerns in one place / one concern in many places
Conceptual integrityOne coherent set of design ideas across a system (Brooks 1975)
ConnascenceTwo elements must change together to stay correct (Page-Jones)
Strength / degree / localityConnascence axes: how hard to refactor, how many affected, how far apart
Static / dynamic connascenceVisible in source / visible only at runtime
Cyclomatic complexityNumber of independent paths, v = e - n + 2p (McCabe 1976)
LCOMLack of Cohesion of Methods
gocyclo / go-arch-lintGo tools: cyclomatic complexity; dependency rules between components
phpmetrics / deptracPHP tools: metrics report; layer dependency rules
Distributed monolithServices that must change and deploy together
Chatty APIFine-grained remote calls that multiply latency and failure

References ​

Built by Morteza Negahi