Skip to content

Software Architecture vs Software Design: Goals, History & Roles ​

"Software design, viewed as a life cycle activity, is the application of software engineering discipline in which software requirements are analyzed to define the software's external characteristics and internal structure as the basis for the software's construction." — SWEBOK Guide V4.0, Chapter 3 Software Design, IEEE Computer Society, October 2024

Summary: Architecture and design are one continuous activity seen at different zoom levels: architecture fixes the few decisions that are expensive to reverse, design fills in everything below them, and both exist to keep the cost of the next change low. Focus: The definitions (SWEBOK v4, IEEE 1471 / ISO 42010, Fowler, Martin), the history from 1968 to today, the three levels of design, who does what, design artifacts (ADRs, diagrams, interfaces, prototypes), the cost-of-change curve, big design up front versus emergent design, technical debt as design debt, and one feature designed at three levels in Go and Laravel. Learning goal: Given any decision on a project, say which level it belongs to, how hard it is to reverse, who should make it, where it must be written down, and which chapter of this path teaches the tools to make it well.

This is the entry page of the Software Design path. It does not teach any single technique; it gives you the vocabulary and the map. The techniques follow: process in The Design Process, quality in Design Quality, principles in SOLID, patterns in Design Patterns. The system-level view lives in the other two paths: the Architecture path (styles, trade-offs, microservices) and the System Design path (capacity, scaling, building blocks). This page explains where the borders between the three paths are.

Page map ​

If you are looking forGo to
The whole page in a few tablesEverything in one minute
Why we separate these two words at allWhy the distinction exists
NATO 1968, Parnas, GoF, Agile, ADRs, SWEBOK v4Where it comes from
Precise definitions, one block eachThe concepts, one by one
Architect, designer, senior engineerRoles
ADRs, diagrams, interfaces, prototypesDesign artifacts
Waterfall, iterative, continuousDesign in the life cycle
Cost of change, flattening itThe cost-of-change curve
Big design up front vs emergent designBDUF vs emergent
Technical debt as design debtTechnical debt
One feature at three levels, Go and LaravelGo, Laravel
What each of the 27 chapters teachesReading map of this path
How this path meets Architecture and System DesignNeighbouring paths
Monolith to distributed systemIn architecture
Exercise with measurable outputLab
Wrong beliefs, cheat sheet, self-check, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

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

TermIn plain wordsTiny exampleWhat goes wrong without it
Software designDeciding how the software will be structured so it can be built"Orders and pricing are two modules; orders asks pricing for a quote"Structure appears by accident, one hack at a time
Software architectureThe fundamental structure and the decisions behind it"One deployable, two modules, one PostgreSQL"Nobody can say why the system looks the way it does
Architectural designThe widest level: style, boundaries, quality trade-offsModular monolith vs microservicesAn expensive decision made implicitly
High-level designComponents, their interfaces and interactionspricing.Quote(tier, lines)Teams guess each other's interfaces
Detailed designThe inside of one component: classes, algorithms, data structuresRules.Apply rounds down, integer centsBugs in the rules, untestable code
ADRA one-page record of one decision and its reasonsADR-0007: modular monolithThe next person reverses a decision for forgotten reasons
Cost of changeHow expensive it is to alter a decision laterRenaming a function vs splitting a databaseSurprise: "a small change" takes a quarter
Technical debtInternal-quality shortfall that taxes every future changeA tangled module structure adds 2 days per featureVelocity falls and nobody can explain why

Architecture vs design in one table.

QuestionArchitectureDesign (below architecture)
ScopeThe system in its environmentOne component or module and below
Typical decisionStyle, deployment units, data ownership, technology that is costly to swapInterfaces, classes, algorithms, error handling
Reversal costHigh (weeks to quarters, many teams)Low to medium (hours to weeks, one team)
Main audienceStakeholders, all teams, operationsThe team that owns the component
Typical artifactADR, context and container diagram, quality scenariosModule API, sequence diagram, class sketch, tests
Primary skillTrade-off analysis between quality attributesModelling, abstraction, patterns, refactoring
Where in this siteArchitecture pathThis path

Three levels, one feature (full example in Go and Laravel):

LevelDecision for "gold customers get 10% off over 100 EUR"Reversal cost
1. ArchitecturePricing is a module of a modular monolith, called in-process; decision recorded as ADR-0007Weeks: split would need a network contract
2. Module designordering depends on a small Pricer interface; pricing exposes one facade and hides internal/Days: change the facade, update one adapter
3. Function designRules.Apply(tier, subtotal) is pure, integer cents, rounds downMinutes: edit one table-tested function

Why the distinction exists ​

Every non-trivial program has a structure, whether anyone chose it or not. People separate "architecture" from "design" because decisions differ in two things: how much of the system they touch and how hard they are to undo. A decision that touches everything and is hard to undo deserves a meeting, a record and a review. A decision that touches one function deserves a unit test and a pull request. Mixing the two wastes meetings on trivia and lets expensive decisions slip through as trivia.

Treat everything as architectureTreat everything as just code
Slow: every rename needs a committeeFast at first: nobody asks permission
Documents rot because they are hugeNo record of why anything is the way it is
Risk: "ivory tower" designs nobody followsRisk: the structure nobody chose becomes the architecture
Good for: safety-critical systems with long lifeGood for: prototypes you will throw away
Architecturalstyle, boundaries,quality trade-offsHigh-levelcomponents, interfaces,data formats, protocolsDetailed (low-level)classes, algorithms, data structures,function signatures, error handlingHard to reverse, few decisionsWho: architect + senior engineers + stakeholdersArtifact: ADR, context/container diagramReversible with a planWho: tech lead + teamArtifact: module API, OpenAPI, sequence diagramCheap to change, many decisionsWho: every developer, every dayArtifact: code, tests, CRC card, class sketchmore scope, fewer decisions, higher cost to undo

The picture is the pyramid used by SWEBOK v4: three stages of design, with the architectural stage at the top (few decisions, expensive to reverse) and detailed design at the bottom (many decisions, cheap to change).

The analogy we reuse on this page: building a house. The decision "wood frame or brick, one storey or two, where the load-bearing walls go" is architecture: changing it after the walls are up means demolition. Where the sockets go in a room is design: annoying to change, possible. Which colour to paint the kitchen is detail: change it on Saturday. Software differs in one important way: Fowler quotes Ralph Johnson saying "There is no theoretical reason that anything is hard to change about software", so much of what is hard to change in software is hard because we made it so, usually through complexity and duplication.

Three common misunderstandings, up front ​

  1. "Architecture is the boxes-and-arrows diagram; design is the code." No. A diagram is one representation. Architecture is the set of significant decisions (and the structures they create), whether drawn or not.
  2. "Architects design; developers just implement." The two stages overlap and feed each other. SWEBOK v4 says: "there are no strict boundaries between stages regarding what must be done and when."
  3. "Agile means no design." The Agile principles say the opposite: "Continuous attention to technical excellence and good design enhances agility." What changed is when and how much you decide, not whether you design.

Where it comes from ​

1968NATO conference;Dijkstra on GOTO1970 / 1972Royce waterfall;Parnas: hiding1974Structured Design:coupling, cohesion1980sObject-orienteddesign, CRC cards1994GoF Design Patterns(23 patterns)1990s - 2000Architecture as discipline;IEEE 1471 (2000)2001Agile Manifesto,XP: flat change cost2003 / 2004Fowler: Who Needs anArchitect; Is Design Dead?2011Nygard: ADRs;Screaming Arch.2014Microservices article;evolutionary design2022ISO/IEC/IEEE 42010revised edition2024SWEBOK v4: separateArchitecture KA

NATO, 1968. The term software engineering and the idea of a "software crisis" come from the 1968 NATO conference at Garmisch, Germany (the report's table of contents has a whole section "4. DESIGN", covering design criteria, strategies and "feedback through monitoring and simulation"). Wikipedia says the term "software crisis" "was coined by some attendees at the first NATO Software Engineering Conference in 1968" (secondary source; we read the proceedings' table of contents).

Dijkstra, 1968. Edsger Dijkstra's letter Go To Statement Considered Harmful (CACM, 1968) is the best-known step of structured programming: control flow built from sequence, selection and iteration. It moved design thinking from "make it run" to "make it understandable".

Royce, 1970. Winston Royce's Managing the Development of Large Software Systems (IEEE WESCON, August 1970) drew the analysis → coding → testing steps that became the "waterfall" picture. Read it before repeating the cliché: right after the simple figure he writes:

"I believe in this concept, but the implementation described above is risky and invites failure." — Winston W. Royce, Managing the Development of Large Software Systems, WESCON 1970

He then draws the iterative relationship between successive phases (his Figure 3) and explains why: the testing phase at the end "is the first event for which timing, storage, input/output transfers, etc., are experienced as distinguished from analyzed", and "the design iterations are never confined to the successive steps".

Parnas, 1972. On the Criteria To Be Used in Decomposing Systems into Modules (CACM, December 1972) compared two ways to split one program and gave the foundation of module design:

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

Split by decisions likely to change, not by processing steps. That is information hiding, the root of everything in Design Quality and SRP.

Stevens, Myers, Constantine, 1974. Structured Design (IBM Systems Journal) gave us coupling and cohesion as measurable properties of a design.

Object-oriented design, 1980s. Classes, inheritance and polymorphism became the dominant way to carve a system; CRC cards (Beck and Cunningham, OOPSLA 1989) gave a paper technique for it (see The Design Process and OO Modeling).

GoF, 1994. Design Patterns: Elements of Reusable Object-Oriented Software by Gamma, Helm, Johnson and Vlissides was first published on 21 October 1994 with 23 patterns (Wikipedia, secondary). It gave designers a shared vocabulary for mid-level structure (Patterns).

Software architecture as a discipline, 1990s. SWEBOK v4 describes the shift: "During the mid-1990s, however, software architecture emerged as a broader discipline involving a more generic study of software structures and architectures." It also records the earlier, structure-only definition from 1990 ("The organizational structure of a system or component", IEEE Std 610.12-1990) and why it was too narrow.

IEEE 1471-2000, ISO/IEC 42010. The IEEE approved Std 1471-2000 in September 2000; it was adopted by ISO/IEC in 2007 and superseded by ISO/IEC/IEEE 42010:2011 (and, per SWEBOK v4's reference list, a 2022 edition exists). Its definition is quoted in the concepts.

Agile and XP, 2001 onwards. The Agile Manifesto (2001) and Extreme Programming argued that, if the cost of change can be kept low, design can be spread over the whole project. Fowler's Is Design Dead? (May 2004) explains the argument and its dependency on testing, continuous integration and refactoring (below).

Fowler, 2003. Who Needs an Architect? (IEEE Software, 2003) turned the definition into a social one: architecture is the shared understanding the expert developers have of the system design, or "things that people perceive as hard to change".

Nygard, 2011. Documenting Architecture Decisions (15 November 2011) proposed one short file per significant decision, the ADR. It made architecture compatible with agile: small, modular documents that "have at least a chance at being updated."

Microservices, 2014 and after. Lewis and Fowler's article (25 March 2014) described systems as "suites of independently deployable services", pushing service boundaries to the front of architectural design; Fowler's Monolith First (3 June 2015) warned that "Almost all the cases where I've heard of a system that was built as a microservice system from scratch, it has ended up in serious trouble." Evolutionary architecture (Parsons, Ford, Kua) frames architecture as supporting "guided, incremental change as a first principle across multiple dimensions".

SWEBOK v4, 2024. The 2024 edition split what had been one chapter into two: "In contrast to the previous edition, this edition creates a software architecture knowledge area (KA), separate from the Software Design KA, because of the significant interest and growth of the discipline since the 1990s." The Design KA still lists architectural design as the first of three design stages and refers readers to the Architecture KA for it.

text
     Year   Idea                                    What changed in practice
1    1968   Structured programming, "crisis"        Control flow you can reason about
2    1970   Royce's phases (and his warning)        Phases named; feedback between them
3    1972   Parnas: hide decisions                  Modules by change, not by step
4    1974   Coupling and cohesion                   Designs become comparable
5    1980s  Objects, CRC cards                       Responsibility-driven design
6    1994   GoF patterns                            Shared names for mid-level structure
7    2000   IEEE 1471                               Architecture has a standard definition
8    2001   Agile, XP                               Design spread over time, protected by tests
9    2011   ADRs                                    Decisions recorded in the repo
10   2014   Microservices                           Boundaries become deployment units
11   2024   SWEBOK v4                               Architecture and Design are separate knowledge areas

The concepts, one by one ​

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

Software design (four senses) Must-know ​

In plain words: design is deciding how the software will be organised so that people can build it, change it and live with it.

Common misunderstanding: "Design is a document you write before coding." SWEBOK v4 lists four senses of the word: (1) the discipline, (2) the processes of that discipline, (3) the result of applying it, and (4) the stage in the life cycle where those processes produce results. A document (the software design description, SDD) is only one possible form of the third sense.

Definition: SWEBOK v4 (Software Design KA): the transformation of "customer and other requirements, needs, and concerns into implementable design specifications". The SDD is "a blueprint or model of the system" that records "the refinement of that software into components, the organization of those components, and the definition of interfaces among them and between the software and the outside world — to a level of detail that enables their construction."

text
     Requirement              Design decision                                  Result (sense 3)
1    "gold gets 10% off"      pricing is a module; discount is a pure rule     module API + rule table
2    "must survive restart"   orders stored in PostgreSQL via a Store port       schema + interface
3    "audit every price"      Quote returns subtotal, discount, total           data shape that can be logged

Real scenario: a team adds "coupons". Where does the rule live (pricing or ordering)? Does coupon validation call another service? What happens when the coupon service is down? Every answer is a design decision, written down or not.

What provides it:

ContextWhere design decisions live
GoPackage boundaries, exported identifiers, small interfaces, internal/
LaravelModule folders, service providers, Actions, Contracts, events
Java / SpringPackages, module-info.java, @Service beans
.NETAssemblies, internal visibility, DI registrations
AnyAn ADR plus tests that enforce it

Fix / how to use it: write the decision where the next person will look (ADR, README of the module, interface comments) and check it with a test; see Go and Laravel.

Software architecture (the definitions) Must-know ​

In plain words: the architecture is the part of the structure and the decisions that everything else depends on.

Common misunderstanding: "There is one correct definition." The field uses several, and each stresses something different. Know all four and say which you mean.

Definition: four definitions, each from a source we read:

SourceWording (quoted)Emphasis
IEEE Std 1471-2000 (via Wikipedia's page on the standard)"The fundamental organization of a system embodied in its components, their relationships to each other, and to the environment, and the principles guiding its design and evolution."Structure plus principles
ISO/IEC/IEEE 42010 (as quoted in SWEBOK v4)"fundamental concepts or properties of a system in its environment embodied in its elements, relationships, and in the principles of its design and evolution"What is fundamental, in an environment
Fowler (Who Needs an Architect?, 2003)"things that people perceive as hard to change"; also "the expert developers working on that project have a shared understanding of the system design"Cost and social agreement
Ralph Johnson, via Fowler"Architecture is about the important stuff. Whatever that is."Deciding what matters
Martin (Screaming Architecture, 2011)"Your architectures should tell readers about the system, not about the frameworks you used in your system."Intent: use cases first, tools deferred

About "architecture is about intent": we did not find that exact slogan in the primary text we read (Martin's 2011 and 2012 blog posts). The passages that carry the idea are in the table: the structure should show the system's purpose, and "A good software architecture allows decisions about frameworks, databases, web-servers, and other environmental issues and tools, to be deferred and delayed."

text
     Reading of "architecture"          Question it answers                     Example answer
1    IEEE 1471 / ISO 42010              What is fundamental, in what context?    Modules, data ownership, deployment
2    Fowler: hard to change             What will hurt if we are wrong?          Database engine, service split
3    Fowler/Johnson: important stuff    What must everyone understand?           The module map and the rules
4    Martin: intent                     What is this system for?                 Folder names say "ordering", not "mvc"

Real scenario: two teams argue whether "use Redis for sessions" is architecture. By Fowler's test (is it hard to change?) probably not, if sessions sit behind an interface. By ISO's test (is it fundamental?) it depends on whether availability depends on it. The argument itself is the point: decide what is architectural and spend your care there.

What provides it: every product has a default shape: Laravel's default application is a layered monolith with MVC, Go's standard project layout is packages with cmd/ and internal/, Spring Boot is layered beans. These are defaults, not decisions; a decision is when someone chose against alternatives and wrote down why.

Fix / how to use it: pick the definition that fits the conversation and say so ("by the cost definition, this is design"). Record only decisions that pass a test: do they affect structure, non-functional characteristics, dependencies, interfaces or construction techniques (Nygard's list)?

Levels of design Must-know ​

In plain words: three zoom levels: the whole system, the components and their conversations, the inside of one component.

Common misunderstanding: "Low-level" means "less important". It means smaller scope. A wrong rounding rule in the lowest level can cost more money than a wrong choice of web framework.

Definition: SWEBOK v4 names three stages: architectural design ("the fundamentals of the system as a whole and in relation to its environment"), high-level design ("outward-facing", the "top-level structure and organization of the software, identifying its various components and how that software system and its components interact with the environment"), and detailed design ("inward-facing", "specifying each component in sufficient detail to facilitate its construction"). It adds that "Not all stages are found in every software process" and that, for example, the sort algorithm may be left to programmers in one system but be "architecturally significant" in another.

text
     Level            Typical questions                                           Typical output
1    Architectural    Monolith or services? One DB or many? Sync or async?         ADRs, container diagram
2    High-level       Which modules? What does each expose? Which events?          Module APIs, sequence diagrams
3    Detailed         Which classes? Which algorithm? Which error type?            Code, tests, class sketch

Real scenario: "Send an invoice after checkout." Level 1: asynchronous via an outbox, because email must not fail checkout. Level 2: ordering publishes OrderPlaced, invoicing consumes it. Level 3: the InvoiceNumber generator is idempotent.

What provides it (per level):

LevelGoLaravelTool or artifact
ArchitecturalModule layout, number of binaries under cmd/App vs modules vs services; queuesADR, C4 container diagram
High-levelExported API of each package; interfaces at consumersModule facades, Contracts, eventsOpenAPI/AsyncAPI, sequence diagram
DetailedTypes, functions, testsClasses, Eloquent models, ActionsCode, CRC cards, table tests

Fix / how to use it: when a decision feels stuck, ask "which level is this?" and move it: either zoom out (it affects other teams, write an ADR) or zoom in (it is local, just change it and test).

Roles: architect, designer, senior engineer Important ​

In plain words: the titles vary by company; what matters is who owns which kind of decision and who must be consulted.

Common misunderstanding: "The architect decides, the others comply." Fowler's article describes the opposite ideal: architecture as shared understanding of the expert developers, and the architect as the person who spots what is important and keeps those parts in good condition. SWEBOK v4 treats architecting as a creative process in which "architects make many decisions that profoundly affect" the downstream process.

Definition: a working split (our synthesis; titles differ per company, treat it as a starting table, not a standard):

AspectArchitectDesigner (tech lead / module owner)Senior engineer
ScopeSystem in its environment, often several teamsOne module or serviceOne feature, one component
Main outputADRs, quality-attribute scenarios, boundaries, guardrailsModule API, internal structure, test strategyWorking code, tests, refactorings, reviews
HorizonQuarters to yearsWeeks to monthsDays to weeks
Key question"What is hard to change and is it right?""What does this module promise and hide?""Is this the simplest thing that works and is it tested?"
Failure modeIvory tower, slidewareOver-engineered moduleLocal optimum, ignoring boundaries
Feedback sourceOperations, incidents, cost, roadmapCallers of the moduleTests, code review, production
text
     Decision                                  Decides                     Must consult
1    Use PostgreSQL for orders                 Architect                   Operations, owning team
2    Pricing exposes Quote(tier, lines)        Pricing module owner        Ordering team (caller)
3    Round discounts down                      Senior engineer             Finance (business rule owner)
4    Rename a private helper                   Anyone                      Nobody

Real scenario: in a team of six the same person may play all three roles in one day: draft an ADR in the morning, sketch a module API at noon, refactor a function after lunch. The roles are hats; what matters is knowing which hat you wear for each decision.

What provides it: CODEOWNERS (GitHub, GitLab) maps paths to owners; architecture decision records record who decided; design reviews and pull requests are the feedback channel.

Fix / how to use it: write the table above for your team, with names, and put it in the repository README.

Design artifacts Must-know ​

In plain words: a design artifact is anything written, drawn or built to think about or communicate a design.

Common misunderstanding: "More documents mean better design." Nygard's reason for ADRs is the opposite: "Large documents are never kept up to date. Small, modular documents have at least a chance at being updated."

Definition: the artifacts a project needs, with their purpose (the first four are the classic set; tests and fitness tests are design artifacts too):

ArtifactWhat it capturesLevelLifetimeExample in this page
ADR (architecture decision record)One decision: context, decision, consequences, statusArchitecturalPermanent, superseded not editedADR-0007 below
Diagram (context, container, sequence, class)Structure or interaction at one level of zoomAllAs long as it is cheap to updateThe four SVGs here
Interface / contract (Go interface, PHP interface, OpenAPI, protobuf)What a component promisesHigh-levelVersioned; breaking changes are decisionsPricer, PricingApi
Prototype / spikeAn experiment to answer one design questionAllThrow away after learningA 50-line spike of the discount rule
Tests as designExecutable examples of the contractDetailedLives with the codediscount_test.go, Pest tests
Architecture fitness testAn automated check of an architectural ruleArchitecturalLives with the codearch_test.go, ArchitectureTest.php

An ADR in Nygard's style (our example, one page):

text
ADR-0007: Pricing is a module of the monolith, not a service
Status:       Accepted (2026-03-02)
Context:      Orders and pricing change together in most releases. One team.
              No independent scaling need. Network call would add latency and
              a failure mode to every checkout.
Decision:     Keep pricing in-process behind a facade. Enforce the boundary
              with an architecture test. Revisit if a second team owns pricing
              or checkout p99 is dominated by pricing CPU.
Consequences: + simple deploys, atomic DB transaction with orders
              - pricing cannot scale or fail independently
              - boundary discipline is enforced by tests, not by the network

Nygard's own wording of what deserves a record: "architecturally significant" decisions, "those that affect the structure, non-functional characteristics, dependencies, interfaces, or construction techniques." If a decision is reversed, "we will keep the old one around, but mark it as superseded."

Real scenario: a new hire asks "why is pricing not a service?" The answer is a link, not a meeting. Six months later checkout p99 triggers the ADR's revisit clause; the team supersedes ADR-0007 with ADR-0019.

What provides it:

ArtifactTools
ADRMarkdown files under docs/adr/; adr-tools; Log4brains
DiagramMermaid, PlantUML, Structurizr (C4), draw.io, plain SVG (UML)
Interface contractGo interface, PHP interface, OpenAPI (REST), AsyncAPI (events), protobuf (gRPC)
PrototypeA scratch branch, a Go test file, a Laravel Tinker session
Fitness testGo go/parser test, Pest arch(), deptrac for PHP, ArchUnit for Java

Fix / how to use it: start with three: one ADR for the biggest decision, one diagram per level you actually use, one test that enforces one boundary.

Design in the life cycle Important ​

In plain words: design is not a phase that ends; how much of it happens up front depends on how fast you can get feedback.

Common misunderstanding: "Waterfall = design first, Agile = no design." Royce's own paper added iteration and feedback loops to the waterfall picture; Agile teams still design, in smaller pieces, closer to code.

Definition:

AspectWaterfall (sequential)Iterative / incrementalContinuous (CI/CD, evolutionary)
When architecture is decidedAlmost all at the startSkeleton first, refined per iterationThin first slice, then evolve; record decisions as they are made
When detailed design is decidedBefore coding, per componentDuring each iterationJust in time, with the code and tests
Feedback on a design decisionLate (integration, test phase)End of each iteration (weeks)Minutes (tests) to days (production metrics)
Design artifactLarge design documentModels plus working incrementADRs, tests, fitness functions, code
Biggest riskDesign built on wrong assumptions, found lateArchitecture erodes between iterationsLocal decisions drift without guardrails
FitsSafety-critical, fixed contracts, hardwareMost product teamsWeb services, platforms, frequent releases
text
     Waterfall:      requirements -> design -> code -> test -> release         (one long loop)
     Iterative:      [req -> design -> code -> test] x N iterations             (loop per iteration)
     Continuous:     design <-> code <-> test <-> deploy <-> observe            (loop per change)

Real scenario: a hospital device firmware may need the waterfall's paper trail; a shop checkout runs continuous delivery and records ADRs. Both do architectural, high-level and detailed design; they differ in the loop length.

What provides it (per product): CI systems (GitHub Actions, GitLab CI) run the fitness tests on every commit; feature flags (LaunchDarkly, Unleash, Laravel Pennant) let design experiments reach production safely.

Fix / how to use it: choose the loop length your domain tolerates, then make the loop shorter than you think you need.

The design-implementation feedback loop Must-know ​

In plain words: you cannot finish a design before you write code, because code tells you which parts of the design were wrong.

Common misunderstanding: "Implementation is mechanical translation of the design." The Royce quote above is the historical proof: the testing phase is where timing, storage and I/O are "experienced as distinguished from analyzed". Design is hypothesis; code and tests are the experiment.

Definition: the loop in which a design decision is implemented, exercised by tests and production, and then corrected.

text
     Step   Design side                                   Implementation side
1    1      Decide: pricing is a module                    
2    2                                                      Write facade + adapter; a cycle appears
3    3      Learn: ordering needs its own Pricer type       Move the interface to the consumer
4    4      Record: update ADR-0007 consequences            Add arch test: no import of pricing
5    5                                                      Ship; checkout p99 stays flat
6    6      Learn: finance wants discount audit             Add Quote.DiscountCents field (API change)

Real scenario: a team draws a clean three-module diagram. The first integration test needs three modules to share one transaction, which the diagram forbids. The design is changed (shared transaction at the composition root), not the test.

What provides it: tests (unit, contract, integration), spikes, trunk-based development, preview environments, observability (production observability gives the slowest and most honest feedback).

Fix / how to use it: pick the thinnest vertical slice that touches every level (UI to database), build it first (a "walking skeleton"), and keep the design document in the repository next to the code.

The cost-of-change curve Must-know ​

In plain words: the later you change a decision, the more it costs, unless you work to keep that cost low.

Common misunderstanding: "The curve is a measured law." It is a model. Fowler states the classical version ("as the project runs, it becomes exponentially more expensive to make changes") and then the XP claim that it can be flattened. Scott Ambler, whose essay shows the curves, notes that Beck's flat curve was "based on his own anecdotal evidence and initially presented as a metaphor", and that the real curve "doesn't completely flatten but in fact rises gently over time". The diagram is illustrative, not data.

Definition: the cost of changing a decision as a function of time or of the number of things that depend on it.

decision point (e.g. database engine)requirementsdesigntestsreleaseprodcost of changing a decisionSerial process, late feedbackHard-to-reverse decisionTests + CI + refactoringshort feedback loop flattens the curveDB engine, service split, public API

Fowler: "The fundamental assumption underlying XP is that it is possible to flatten the change curve enough to make evolutionary design work." Which practices flatten it (Fowler, Is Design Dead?): testing and continuous integration at the core ("Without the safety provided by testing the rest of XP would be impossible"), and disciplined refactoring. Ambler's summary of the mechanism: the curve flattens "because we follow techniques which reduce the feedback cycle."

text
     Decision                          Cost to change at week 1      Cost to change at month 12
1    Name of a private function        seconds (IDE rename)          seconds (IDE rename)
2    Discount rounding rule            minutes (edit + test)         hours (data fix, re-invoice?)
3    Module boundary                    hours                         weeks (callers, tests, teams)
4    Database engine                    days                          quarters (data, ops, tooling)
5    Public API contract                hours                         years (clients you do not control)

Real scenario: a startup changes its primary key type from integer to uuid in week 2 (one migration) and in year 3 (backfills, foreign keys, partner integrations). The decision is the same; the surrounding web of dependants is not.

What flattens it, per tool:

TechniqueWhat it does for costProduct or tool
Automated testsDetects breakage in minutesgo test, Pest, PHPUnit
Continuous integrationMerges small changes dailyGitHub Actions, GitLab CI
RefactoringKeeps structure matching understandingJetBrains GoLand/PhpStorm, gopls rename
Small interfaces and hidden internalsLimits who depends on whatGo internal/, PHP Internal namespace plus Pest arch()
Zero-downtime migrationsMakes data changes cheapSchema migrations
Feature flagsSeparates deploy from releaseLaravel Pennant, Unleash

Fix / how to use it: list your five most expensive decisions to reverse; for each, either decide it carefully (and write an ADR) or add an indirection that makes it cheaper (an interface, an adapter, an expand-contract migration).

Big design up front vs emergent design Important ​

In plain words: BDUF means designing most things before coding; emergent (evolutionary) design means letting the structure grow with the code and the tests.

Common misunderstanding: "You must pick one." Fowler, quoting Jim Highsmith: "In one tray is planned design, the other is refactoring. In more traditional approaches planned design dominates because the assumption is that you can't change your mind later. As the cost of change lowers then you can do more of your design later as refactoring. Planned design does not go away completely, but there is now a balance of two design approaches to work with."

Definition:

AspectBig design up frontEmergent / evolutionary design
AssumptionChanging later is very expensiveChanging later can be made cheap
NeedsStable, well-understood requirementsTests, CI, refactoring discipline
StrengthCatches costly mistakes before code existsLearns from working software
WeaknessDesigns for requirements that change; wasted workWithout discipline: "code and fix", entropy
Fowler's positionPrefers planned design to "code and fix"Seeks the balance; "Design does not go away"
Typical failureSpeculative generality (YAGNI violated)Local decisions, no one watching architecture
text
     Situation                                       Lean toward
1    Public API, data model, regulated process        Up-front design, then protect with tests
2    Internal module behind an interface              Emergent: start simple, refactor
3    Technology you cannot swap cheaply (database)    Decide deliberately, write an ADR
4    UI layout, copy, rules still being discovered    Emergent: ship thin, learn
5    Safety-critical subsystem                        Up-front plus formal review

Fowler's Design Stamina Hypothesis (20 June 2007) says design pays back: "You can save short-term time by neglecting design, but this accumulates TechnicalDebt which will slow your productivity later. Putting effort into to the design of your software improves the stamina of your project, allowing you to go faster for longer." (Spelling as in the source.)

Real scenario: the team decides the shape up front (modular monolith, one database, public REST contract) and lets the inside of each module emerge. That is the split this page uses in the Go and Laravel sections.

What provides it: YAGNI ("You Aren't Gonna Need It", an XP practice Fowler discusses on his bliki) limits speculation; ADRs and fitness tests limit drift.

Fix / how to use it: design up front the things on your "expensive to reverse" list, and let the rest emerge under tests.

Technical debt as design debt Must-know ​

In plain words: when the structure no longer matches what the team understands, every change costs more; that extra cost is interest.

Common misunderstanding: "Technical debt means bad code we will fix later." Fowler: "Technical Debt is a metaphor, coined by Ward Cunningham, that frames how to think about dealing with this cruft, thinking of it like a financial debt. The extra effort that it takes to add new features is the interest paid on the debt." His example: with a clear module structure a feature takes four days; with the cruft, six; "The two day difference is the interest on the debt." Some debt is deliberate and pays for speed; some is just mess. SWEBOK v4 adds: "Architectural technical debt has been introduced to reflect that today's decisions for an architecture may have significant consequences later in the software system's life cycle."

Definition: design debt is the gap between the structure the code has and the structure the team needs for the changes it expects. Two axes (Fowler's Technical Debt Quadrant): deliberate vs inadvertent, reckless vs prudent.

QuadrantExampleResponse
Deliberate, prudent"Ship with one DB per module sharing a schema; split after launch"Record an ADR with a revisit date
Deliberate, reckless"We have no time for design"Stop; this is how velocity dies
Inadvertent, prudent"Now we know how we should have modelled orders"Refactor as part of next feature
Inadvertent, recklessGod class nobody understandsCharacterise with tests, then split (SRP)
text
     Feature   Days with clear modules   Days with cruft   Interest
1    A         4                         6                 2
2    B         4                         6                 2
3    C         4                         6                 2
4    Cleanup   5 once                    -                 pays back after feature C

Real scenario: a User model with 3,000 lines gets a feature every sprint; each feature takes longer, and every deploy risks an unrelated screen. The interest is paid in estimates, bugs and fear.

What provides it: metrics and tools surface the debt: change-coupling from git log (see SRP mechanics), static analysis (PHPStan/Larastan, go vet, staticcheck), churn and complexity reports.

Fix / how to use it: keep a debt list tied to the features that pay the interest; pay principal in the same pull request as the next feature that touches the area (the "boy scout" move), and use refactoring.

Reversibility and architecturally significant decisions Good to know ​

In plain words: before you decide, ask "if this is wrong, how do we get out?"

Common misunderstanding: "Every decision deserves the same care." The point of the three levels is to spend care where reversal is expensive.

Definition: a decision is architecturally significant when it is expensive to reverse or affects many parts of the system. A simple rating: reversal time (hours, days, weeks, quarters) times number of teams touched.

DecisionReversal timeTeams touchedTreat as
Library for retryHours1Design, no ADR
Message broker (RabbitMQ vs Kafka)WeeksSeveralADR
Primary database engine (PostgreSQL vs MySQL vs MongoDB)QuartersAllADR + spike
Public REST path structureYearsExternal clientsADR + versioning policy
Splitting into microservicesQuartersAllADR + boundaries study

Real scenario: choosing between RabbitMQ and Kafka looks like a technology choice; it is an architecture choice because consumers, ordering guarantees and operations depend on it.

What provides it: interfaces, adapters and ports (hexagonal ideas, see DIP) turn some "quarters" decisions into "weeks".

Fix / how to use it: when you cannot reverse cheaply, delay (decide at the last responsible moment), prototype, or add an indirection.

Roles, artifacts and the loop together ​

A change request touches all of the above. The walk-through uses the discount feature:

text
     Step   Who                    What happens                                           Artifact
1    1      Product                "Gold customers get 10% off over 100 EUR"              Ticket
2    2      Architect + team       Does it fit current boundaries? Yes: pricing module     ADR-0007 referenced
3    3      Module owner           Add Rules type; facade stays stable                     Interface unchanged, PR
4    4      Senior engineer        Write table test first, then Apply                      discount_test.go
5    5      CI                     arch_test.go: no new cross-module import                Green build
6    6      Everyone               Production shows 10% on 3% of orders; finance happy     Metrics

Reading map of this path ​

The path has 27 chapters in five groups. Each line says what the chapter gives you.

#ChapterOne line
01Software Architecture vs Software Design (this page)The vocabulary, history, levels, roles and cost of change
02The Design ProcessConceptual design, CRC cards, technical design and the art of compromise
03Quality Attributes and RequirementsFunctional vs non-functional requirements and the ISO 25010 quality model
04OO Modeling FundamentalsAbstraction, encapsulation, decomposition, generalization, polymorphism
05UML in PracticeThe diagrams that earn their place: class, sequence, state, activity, component, package, deployment
06Design QualityComplexity, coupling and cohesion, information hiding, separation of concerns, conceptual integrity
07Composition and the Law of DemeterBuilding objects from objects without reaching through them
08Code Smells and RefactoringThe 14 smells and the moves that remove them
09Low-Level DesignClasses, responsibilities, relationships, structured vs OO design
10SOLID overviewFive principles for code that survives change
11SRPOne reason to change per module
12OCPExtend behaviour without editing tested code
13LSPSubtypes that keep the supertype's promises
14ISPSmall interfaces shaped by their clients
15DIPDepend on abstractions; invert the arrows
16Design Patterns: IntroductionOrigin, why patterns matter, the three families
17Creational PatternsSingleton, factories, builder, prototype
18Structural PatternsFacade, adapter, composite, proxy, decorator, bridge, flyweight
19Behavioral PatternsStrategy, observer, command, state, template method and the rest
20Patterns in PracticeSelection, combination and anti-patterns in real systems
21Designing for ConcurrencyGoroutines, queues, locks and shared state as design inputs
22Control Flow and Event HandlingWho calls whom: callbacks, events, schedulers
23Data Persistence in DesignRepositories, mapping and boundaries between code and database
24Distribution of ComponentsLocal vs remote, latency and failure as design inputs
25Error Handling and Fault ToleranceExceptions, errors, retries and graceful degradation
26Interaction and PresentationMVC, MVP, MVVM and data flow
27Security by DesignDesigning so that the wrong thing is hard to do

Suggested reading orders:

If you areRead
New to design01 → 02 → 03 → 04 → 06 → 10-15
A developer who writes classes daily06 → 08 → 09 → 10-15 → 16-20
Moving into a lead or architect role01 → 03 → 24 → then the Architecture path
Preparing for interviews10-15, 16-19, 08, then System Design

Neighbouring paths ​

PathQuestion it answersStart with
Software Design (here)How do I structure code and modules so they stay changeable?This page
ArchitectureWhich style and which trade-offs for a whole system?What software architecture is, Architecture decisions and trade-offs
System DesignHow do I size, scale and assemble building blocks for a workload?What system design is, The 4-step approach
Domain-Driven DesignHow do I model the business and draw bounded contexts?Why DDD
DatabasesHow do I store and query the data this design depends on?Schema design
MessagingHow do components talk asynchronously?Messaging fundamentals
text
     Zoom   Path                    Example question about the discount feature
1    wide   System Design           How many quotes per second at Black Friday? Cache them?
2    wide   Architecture            Pricing in-process or as a service? Who owns the rules table?
3    mid    Design (this path)      What does pricing expose? Which interface does ordering need?
4    narrow Design (low level)      How does Apply round? Which type holds money?
5    any    DDD                     Is "price" one concept in sales and in billing?

Rule of thumb: System Design starts from load and constraints, Architecture from quality attributes and trade-offs, Design from responsibilities and change. They meet in the middle; this path teaches the part closest to code.

Mechanics ​

Deciding which level a decision belongs to Must-know ​

A four-question test:

QuestionIf yesThen
Does it cross a team or deployment boundary?ArchitecturalADR, review
Is it expensive to reverse (more than a sprint)?Architectural or high-levelADR or interface review
Does another module or client depend on it?High-levelPublic API; version it
Is it inside one module and covered by tests?DetailedJust do it, in a pull request

Writing an ADR in five minutes ​

SectionQuestion to answerLength
TitleWhat did we decide? (a noun phrase and a verb)1 line
StatusProposed, accepted, superseded by ADR-N1 line
ContextWhat forces are at play: requirements, constraints, people?3-6 lines
DecisionWhat will we do? ("We will ...")2-4 lines
ConsequencesWhat becomes easier, what harder, what do we revisit and when?3-6 lines

Nygard's rules we reuse: store in the repository (doc/arch/adr-NNN.md in his example), numbered sequentially and never reused, plain Markdown, and a reversed decision is marked superseded, not deleted.

Enforcing a boundary with a test ​

A boundary that exists only in a diagram is a wish. The Go and Laravel sections show two tests: one parses imports, the other uses Pest's arch(). Each fails the build when ordering imports pricing's internals. Ford, Parsons and Kua call such automated architectural checks fitness functions; we use the idea and not their definition, since we did not read the book's text, only its publisher page, which defines an evolutionary architecture as one that "supports guided, incremental change as a first principle across multiple dimensions".

Error codes and failure messages you will actually see ​

WhereMessageMeaning
Go compileruse of internal package ... not allowedYou imported another module's internal/ (Go 1.4 rule)
Go test (this page)ordering/x.go imports academy/.../pricing/internal/discount (forbidden by architecture decision)The ADR was violated
Pesta failed arch() expectation naming the offending class and the forbidden namespace (exact wording depends on the Pest version; not verified here)Boundary violated
Laravel containerTarget [App\Modules\Pricing\Api\PricingApi] is not instantiableThe module's service provider is not registered in bootstrap/providers.php

Go ​

The running example is one feature: gold-tier customers get 10% off orders of at least 100 EUR. It is small enough to read in a minute and touches all three levels. The Go code is a runnable module (docs/snippets/design/architecture-vs-design/go); go vet ./... and go test ./... pass.

Level 1: architecture decisionADR-0007: modular monolith, ordering and pricing as modules,in-process call, no network between them (yet).orderingpricingLevel 2: module designordering declares Pricer (what it needs); pricing exposes a facadeand hides internal/. Composition root wires them.PricerinterfaceService.Quote+ internal/Level 3: function designRules.Apply(tier, subtotal): pure, integer cents,rounds down, table-tested.Apply(tier, cents) centsconstrainsconstrains

Before ​

One handler parses, prices, applies the rule, writes to PostgreSQL and answers. Nothing here was decided; the architecture is "whatever this function became", the module design is "none", and the function design hard-codes 10% with unspecified rounding.

go
// Package before shows a checkout handler where architecture, module design
// and function design are all decided in one place, by accident.
package before

import (
	"database/sql"
	"fmt"
	"net/http"
	"strconv"
)

// Checkout prices, discounts, stores and answers in one function. Nobody
// chose this structure; it is what appears when design is skipped.
func Checkout(db *sql.DB) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		qty, _ := strconv.Atoi(r.FormValue("qty"))
		unit, _ := strconv.Atoi(r.FormValue("unit_cents"))
		total := qty * unit
		if r.FormValue("tier") == "gold" && total > 10000 {
			total = total - total/10 // 10% hard-coded, rounding unspecified
		}
		_, err := db.Exec("INSERT INTO orders (total_cents) VALUES ($1)", total)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		fmt.Fprintf(w, "total: %d", total)
	}
}

After ​

Level 1, architecture decision (ADR-0007): pricing and ordering are two modules of one deployable. The decision is enforced by shop/arch_test.go, which parses imports:

go
// Package shop holds the architecture fitness functions: tests that fail the
// build when a level-1 decision (module boundaries) is violated.
package shop

import (
	"go/parser"
	"go/token"
	"io/fs"
	"path/filepath"
	"strings"
	"testing"
)

const module = "academy/architecture-vs-design/shop/"

// importsOf returns every import path used by non-test files under dir.
func importsOf(t *testing.T, dir string) map[string][]string {
	t.Helper()
	out := map[string][]string{}
	err := filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error {
		if err != nil || d.IsDir() || !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") {
			return err
		}
		f, err := parser.ParseFile(token.NewFileSet(), path, nil, parser.ImportsOnly)
		if err != nil {
			return err
		}
		for _, im := range f.Imports {
			out[path] = append(out[path], strings.Trim(im.Path.Value, `"`))
		}
		return nil
	})
	if err != nil {
		t.Fatal(err)
	}
	return out
}

// forbid fails if any file under dir imports a path with the given prefix.
func forbid(t *testing.T, dir, prefix string) {
	t.Helper()
	for file, imps := range importsOf(t, dir) {
		for _, imp := range imps {
			if strings.HasPrefix(imp, prefix) {
				t.Errorf("%s imports %s (forbidden by architecture decision)", file, imp)
			}
		}
	}
}

// ADR-0007: modules talk through public APIs only.
func TestOrderingDoesNotReachIntoPricing(t *testing.T) {
	forbid(t, "ordering", module+"pricing")
}

// ADR-0007: no cycles between modules.
func TestPricingDoesNotKnowOrdering(t *testing.T) {
	forbid(t, "pricing", module+"ordering")
}

Level 2, module design. ordering declares the small Pricer interface it needs and never imports pricing. The pricing module exposes one facade and hides its internals under internal/:

go
// Package ordering is level 2 on the consumer side: it declares the small
// interface it needs from pricing and never imports pricing's internals.
package ordering

import (
	"context"
	"fmt"
)

// Line is an order line as ordering stores it.
type Line struct {
	SKU       string
	Quantity  int64
	UnitCents int64
	Currency  string
}

// Quote is what ordering needs back from a pricing component.
type Quote struct {
	SubtotalCents int64
	DiscountCents int64
	TotalCents    int64
	Currency      string
}

// Pricer is owned by ordering (consumer-side interface, as in Go proverbs:
// accept interfaces). The pricing module satisfies it through an adapter in
// the composition root, so pricing does not import ordering.
type Pricer interface {
	Price(ctx context.Context, tier string, lines []Line) (Quote, error)
}

// Order is the stored result of checkout.
type Order struct {
	ID    int64
	Tier  string
	Lines []Line
	Quote Quote
}

// Store persists orders. The database is a detail behind this interface.
type Store interface {
	Save(ctx context.Context, o Order) (int64, error)
}

// Service is the ordering module's use case.
type Service struct {
	pricer Pricer
	store  Store
}

// NewService builds the use case from its two collaborators.
func NewService(p Pricer, s Store) *Service {
	return &Service{pricer: p, store: s}
}

// Place prices the lines and stores the order. The price is decided by the
// pricing module; ordering only records what it was told.
func (s *Service) Place(ctx context.Context, tier string, lines []Line) (Order, error) {
	q, err := s.pricer.Price(ctx, tier, lines)
	if err != nil {
		return Order{}, fmt.Errorf("ordering: price: %w", err)
	}
	o := Order{Tier: tier, Lines: lines, Quote: q}
	id, err := s.store.Save(ctx, o)
	if err != nil {
		return Order{}, fmt.Errorf("ordering: save: %w", err)
	}
	o.ID = id
	return o, nil
}
go
// Package pricing is level 2: module design. Other modules see only this
// file; everything under internal/ is a private detail they cannot import.
package pricing

import (
	"context"
	"errors"

	"academy/architecture-vs-design/shop/pricing/internal/discount"
)

// Line is one order line as pricing understands it.
type Line struct {
	SKU       string
	Quantity  int64
	UnitCents int64
	Currency  string
}

// Quote is the answer pricing gives to any caller.
type Quote struct {
	SubtotalCents int64
	DiscountCents int64
	TotalCents    int64
	Currency      string
}

// Service is the module's public face (a facade).
type Service struct {
	rules discount.Rules
}

// NewService wires the default rules. A real system would load them from
// configuration owned by the pricing team.
func NewService() *Service {
	return &Service{rules: discount.Rules{
		discount.Gold: {MinSubtotalCents: 10000, PercentOff: 10},
	}}
}

// ErrEmptyOrder is returned when there is nothing to price.
var ErrEmptyOrder = errors.New("pricing: empty order")

// Quote prices lines for a customer tier ("gold", "standard").
func (s *Service) Quote(ctx context.Context, tier string, lines []Line) (Quote, error) {
	if err := ctx.Err(); err != nil {
		return Quote{}, err
	}
	if len(lines) == 0 {
		return Quote{}, ErrEmptyOrder
	}
	q := Quote{Currency: lines[0].Currency}
	for _, l := range lines {
		q.SubtotalCents += l.Quantity * l.UnitCents
	}
	q.DiscountCents = s.rules.Apply(discount.Tier(tier), q.SubtotalCents)
	q.TotalCents = q.SubtotalCents - q.DiscountCents
	return q, nil
}

Level 3, function design. The rule is a pure function over integer cents, tested by a table:

go
// Package discount is level 3: class and function design. It is pure
// (no I/O, no clock, no globals), so every rule is a table-test row.
package discount

// Tier is the customer's loyalty tier.
type Tier string

// Known tiers.
const (
	Standard Tier = "standard"
	Gold     Tier = "gold"
)

// Rule describes one discount: a percentage off orders at or above a floor.
type Rule struct {
	MinSubtotalCents int64
	PercentOff       int64 // whole percent, 0..100
}

// Rules maps a tier to its rule. A missing tier means no discount.
type Rules map[Tier]Rule

// Apply returns the discount in cents for a subtotal. The discount is rounded
// down, so the customer never pays less than the rule promises and the shop
// never gives more. Negative subtotals are treated as zero.
func (r Rules) Apply(t Tier, subtotalCents int64) int64 {
	rule, ok := r[t]
	if !ok || subtotalCents < rule.MinSubtotalCents || subtotalCents <= 0 {
		return 0
	}
	return subtotalCents * rule.PercentOff / 100
}
go
package discount

import "testing"

func TestApply(t *testing.T) {
	rules := Rules{Gold: {MinSubtotalCents: 10000, PercentOff: 10}}
	cases := []struct {
		name     string
		tier     Tier
		subtotal int64
		want     int64
	}{
		{"gold above floor", Gold, 20000, 2000},
		{"gold at floor", Gold, 10000, 1000},
		{"gold below floor", Gold, 9999, 0},
		{"standard has no rule", Standard, 50000, 0},
		{"rounds down", Gold, 10009, 1000},
		{"negative subtotal", Gold, -5, 0},
	}
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			if got := rules.Apply(c.tier, c.subtotal); got != c.want {
				t.Fatalf("Apply(%s, %d) = %d, want %d", c.tier, c.subtotal, got, c.want)
			}
		})
	}
}

The composition root is the only place that knows both modules; it wires them with a small adapter. Swapping the in-process call for an HTTP client later changes this file and nothing else:

go
// Command shop is the composition root: the only place that knows both
// modules and wires one to the other. This is level 1 made executable.
package main

import (
	"context"
	"fmt"
	"log"

	"academy/architecture-vs-design/shop/ordering"
	"academy/architecture-vs-design/shop/pricing"
)

// pricingAdapter lets ordering's Pricer interface be satisfied by the
// pricing module's facade, so neither module imports the other's types.
type pricingAdapter struct{ svc *pricing.Service }

func (a pricingAdapter) Price(ctx context.Context, tier string, lines []ordering.Line) (ordering.Quote, error) {
	pl := make([]pricing.Line, len(lines))
	for i, l := range lines {
		pl[i] = pricing.Line{SKU: l.SKU, Quantity: l.Quantity, UnitCents: l.UnitCents, Currency: l.Currency}
	}
	q, err := a.svc.Quote(ctx, tier, pl)
	if err != nil {
		return ordering.Quote{}, err
	}
	return ordering.Quote{
		SubtotalCents: q.SubtotalCents,
		DiscountCents: q.DiscountCents,
		TotalCents:    q.TotalCents,
		Currency:      q.Currency,
	}, nil
}

// memoryStore is a stand-in for PostgreSQL so the program runs offline.
type memoryStore struct{ next int64 }

func (m *memoryStore) Save(_ context.Context, _ ordering.Order) (int64, error) {
	m.next++
	return m.next, nil
}

func main() {
	svc := ordering.NewService(pricingAdapter{pricing.NewService()}, &memoryStore{})
	o, err := svc.Place(context.Background(), "gold", []ordering.Line{
		{SKU: "KB-01", Quantity: 2, UnitCents: 6000, Currency: "EUR"},
	})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("order %d: subtotal %d, discount %d, total %d %s\n",
		o.ID, o.Quote.SubtotalCents, o.Quote.DiscountCents, o.Quote.TotalCents, o.Quote.Currency)
}

The Go angle ​

Go makes level 1 and level 2 decisions unusually visible because the compiler enforces part of them:

Go featureWhich level it servesWhat it enforces
Package = unit of change and of importArchitectural / high-levelDependencies are explicit import lines; cycles are compile errors
internal/ directoriesHigh-levelThe Go 1.4 release notes: a package under internal "may not be imported by packages outside the source subtree in which they reside"
Unexported identifiersDetailedHiding inside a package
Interfaces satisfied implicitlyHigh-levelThe consumer can declare the interface it needs (ordering.Pricer), so the provider need not import it
cmd/<name>/main.goArchitecturalOne composition root per binary
go list -deps, go vet, go/parserFitness testsImport rules as tests, as in arch_test.go
go test table testsDetailedBehaviour of a function as data

The official module layout guide (go.dev/doc/modules/layout) describes the same shape: a directory named internal for code you are free to refactor, and cmd/ for commands. We read it for the internal and cmd statements; the example layout here follows them.

Laravel ​

The same feature in a Laravel 13 application (PHP 8.4). The files live under docs/snippets/design/architecture-vs-design/php; PHP is not installed on the authoring machine, so the code was reviewed, not run.

Before ​

The classic fat controller: parsing, rule and persistence together, with 10% and the rounding hidden in arithmetic.

php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

// Before: architecture, module and function design all happen by accident in
// one controller method. Nothing here was decided; it simply accumulated.
class CheckoutController extends Controller
{
    public function store(Request $request)
    {
        $total = $request->integer('qty') * $request->integer('unit_cents');

        if ($request->input('tier') === 'gold' && $total > 10000) {
            $total = $total - (int) ($total / 10); // 10% hard-coded
        }

        $id = DB::table('orders')->insertGetId(['total_cents' => $total]);

        return response()->json(['id' => $id, 'total' => $total]);
    }
}

After ​

Level 1, architecture decision (ADR-0007): a modular monolith in one Laravel app: App\Modules\Ordering and App\Modules\Pricing. The boundary is a Pest architecture test (arch(), Pest's architecture-testing API; not->toUse and toOnlyBeUsedIn are documented on pestphp.com/docs/arch-testing):

php
<?php

// Level 1 as a test: the architecture decision "modules talk through public
// APIs only" becomes a fitness function that fails the build when broken.
// Pest architecture testing: https://pestphp.com/docs/arch-testing

arch('ordering does not reach into pricing internals')
    ->expect('App\Modules\Ordering')
    ->not->toUse('App\Modules\Pricing\Internal');

arch('pricing does not know ordering')
    ->expect('App\Modules\Pricing')
    ->not->toUse('App\Modules\Ordering');

arch('pricing internals are private to pricing')
    ->expect('App\Modules\Pricing\Internal')
    ->toOnlyBeUsedIn('App\Modules\Pricing');

Level 2, module design. Pricing\Api is the public contract (an interface and two readonly data objects); PricingService implements it; the service provider is the module's only wiring and is listed in bootstrap/providers.php, the registration file Laravel 13's provider docs describe:

php
<?php

declare(strict_types=1);

namespace App\Modules\Pricing\Api;

/**
 * Level 2: the Pricing module's public contract. Other modules depend on
 * this interface and on the two data objects below, never on Internal\*.
 */
interface PricingApi
{
    /**
     * @param list<QuoteLine> $lines
     */
    public function quote(string $tier, array $lines): Quote;
}
php
<?php

declare(strict_types=1);

namespace App\Modules\Pricing\Api;

final readonly class QuoteLine
{
    public function __construct(
        public string $sku,
        public int $quantity,
        public int $unitCents,
        public string $currency,
    ) {
    }
}
php
<?php

declare(strict_types=1);

namespace App\Modules\Pricing\Api;

final readonly class Quote
{
    public function __construct(
        public int $subtotalCents,
        public int $discountCents,
        public int $totalCents,
        public string $currency,
    ) {
    }
}
php
<?php

declare(strict_types=1);

namespace App\Modules\Pricing;

use App\Modules\Pricing\Api\PricingApi;
use App\Modules\Pricing\Api\Quote;
use App\Modules\Pricing\Internal\DiscountRules;
use InvalidArgumentException;

final class PricingService implements PricingApi
{
    public function __construct(private readonly DiscountRules $rules)
    {
    }

    public function quote(string $tier, array $lines): Quote
    {
        if ($lines === []) {
            throw new InvalidArgumentException('Cannot price an empty order.');
        }

        $subtotal = 0;
        foreach ($lines as $line) {
            $subtotal += $line->quantity * $line->unitCents;
        }

        $discount = $this->rules->discountFor($tier, $subtotal);

        return new Quote($subtotal, $discount, $subtotal - $discount, $lines[0]->currency);
    }
}
php
<?php

declare(strict_types=1);

namespace App\Modules\Pricing;

use App\Modules\Pricing\Api\PricingApi;
use App\Modules\Pricing\Internal\DiscountRules;
use Illuminate\Support\ServiceProvider;

/**
 * The module's only wiring. Register it in bootstrap/providers.php.
 */
final class PricingServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->singleton(DiscountRules::class, fn () => new DiscountRules([
            'gold' => ['min_subtotal_cents' => 10_000, 'percent_off' => 10],
        ]));

        // Callers ask for the interface; the concrete class stays private.
        $this->app->bind(PricingApi::class, PricingService::class);
    }
}

Ordering is one Action class (one use case) plus a thin controller that validates with $request->validate() and delegates:

php
<?php

declare(strict_types=1);

namespace App\Modules\Ordering;

use App\Modules\Pricing\Api\PricingApi;
use App\Modules\Pricing\Api\QuoteLine;
use Illuminate\Support\Facades\DB;

/**
 * Level 2 + 3 in the Ordering module: one use case (Action class).
 * It depends on Pricing's public API only.
 */
final class PlaceOrder
{
    public function __construct(private readonly PricingApi $pricing)
    {
    }

    /**
     * @param list<array{sku: string, quantity: int, unit_cents: int, currency: string}> $lines
     */
    public function handle(string $tier, array $lines): int
    {
        $quote = $this->pricing->quote($tier, array_map(
            fn (array $l) => new QuoteLine($l['sku'], $l['quantity'], $l['unit_cents'], $l['currency']),
            $lines,
        ));

        return DB::transaction(function () use ($tier, $quote): int {
            return DB::table('orders')->insertGetId([
                'tier' => $tier,
                'subtotal_cents' => $quote->subtotalCents,
                'discount_cents' => $quote->discountCents,
                'total_cents' => $quote->totalCents,
                'currency' => $quote->currency,
            ]);
        });
    }
}
php
<?php

declare(strict_types=1);

namespace App\Modules\Ordering;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

final class CheckoutController
{
    public function store(Request $request, PlaceOrder $placeOrder): JsonResponse
    {
        $data = $request->validate([
            'tier' => ['required', 'string', 'in:standard,gold'],
            'lines' => ['required', 'array', 'min:1'],
            'lines.*.sku' => ['required', 'string'],
            'lines.*.quantity' => ['required', 'integer', 'min:1'],
            'lines.*.unit_cents' => ['required', 'integer', 'min:0'],
            'lines.*.currency' => ['required', 'string', 'size:3'],
        ]);

        return response()->json(['id' => $placeOrder->handle($data['tier'], $data['lines'])], 201);
    }
}

Level 3, class design. The rule is a final readonly class with integer cents and no I/O:

php
<?php

declare(strict_types=1);

namespace App\Modules\Pricing\Internal;

/**
 * Level 3: class and function design. Pure, final, integer cents, no I/O.
 * Only the Pricing module may use it (enforced by tests/ArchitectureTest.php).
 */
final readonly class DiscountRules
{
    /**
     * @param array<string, array{min_subtotal_cents: int, percent_off: int}> $rules keyed by tier
     */
    public function __construct(private array $rules)
    {
    }

    public function discountFor(string $tier, int $subtotalCents): int
    {
        $rule = $this->rules[$tier] ?? null;

        if ($rule === null || $subtotalCents <= 0 || $subtotalCents < $rule['min_subtotal_cents']) {
            return 0;
        }

        // intdiv rounds toward zero: the shop never gives more than the rule says.
        return intdiv($subtotalCents * $rule['percent_off'], 100);
    }
}
php
<?php

use App\Modules\Pricing\Internal\DiscountRules;

$rules = new DiscountRules(['gold' => ['min_subtotal_cents' => 10_000, 'percent_off' => 10]]);

it('discounts gold orders at or above the floor', function () use ($rules) {
    expect($rules->discountFor('gold', 20_000))->toBe(2_000)
        ->and($rules->discountFor('gold', 10_000))->toBe(1_000);
});

it('gives nothing below the floor or for unknown tiers', function () use ($rules) {
    expect($rules->discountFor('gold', 9_999))->toBe(0)
        ->and($rules->discountFor('standard', 50_000))->toBe(0);
});

it('rounds down', function () use ($rules) {
    expect($rules->discountFor('gold', 10_009))->toBe(1_000);
});

The Laravel angle ​

Laravel featureWhich level it servesNotes
Service providers and bootstrap/providers.phpArchitectural / high-levelOne provider per module is the module's wiring (Laravel 13 docs, Service Providers)
Service container: bind(Interface::class, Concrete::class)High-levelCallers ask for the interface (container docs show $this->app->bind(EventPusher::class, RedisEventPusher::class))
Form Requests, $request->validate()DetailedInput rules away from business rules
Action classes, Jobs, ListenersHigh-level / detailedOne use case per class
Eloquent modelsDetailedBeware of the god model; see SRP
DB::transactionHigh-levelThe atomic boundary that a modular monolith keeps for free
Pest arch()Fitness testsnot->toUse, toOnlyBeUsedIn
Events and queuesArchitecturalAsynchronous module boundaries (Event-Driven Architecture)

Go and Laravel differ in one design detail worth noticing: in Go, ordering owns the Pricer interface (consumer-side, no import of pricing); in the PHP version, Pricing\Api owns the interface and Ordering imports it. Both are valid; the Go choice removes a compile-time dependency, the PHP choice gives the provider a stable published contract and relies on a test to forbid the internal namespace only.

Solving the classic problems ​

Architecture happens by accident ​

SolutionHowAdvantageCost / limitation
ADR for each significant decisionOne Markdown file per decision in the repositoryReasons survive team changesNeeds a habit; stale ADRs mislead
Architecture review of the pull request templateOne checklist line: "Does this change a boundary?"Cheap, catches driftEasy to ignore without tests
Fitness tests in CIarch_test.go, Pest arch()Boundary is enforced, not hoped forTests must be maintained with the architecture

Design lives only in someone's head ​

SolutionHowAdvantageCost / limitation
Interface comments plus a README per moduleState what the module promises and what it hidesOnboarding in minutesNeeds review like code
C4 or sequence diagram in the repoText-based (Mermaid, PlantUML) or SVG next to the codeDiffable, reviewableDiagrams drift unless cheap to update
Pairing and design reviewsTwo people explain the design before codingShared understanding (Fowler's definition)Calendar time

Boundary erosion ​

text
     Month   Event                                              Result
1    M0      ADR-0007: ordering must not import pricing/internal   arch test green
2    M3      Deadline: a developer imports pricing/internal "just once"  CI red; PR blocked
3    M3      Fix: add Quote.Breakdown to the facade (public)       one more public method, boundary intact
4    M9      Same import added with the test commented out         erosion starts; ADR now false
SolutionHowAdvantageCost / limitation
Compiler or language visibilityGo internal/, Java modules, .NET internalCannot be bypassed casuallyCoarse (package granularity)
Fitness testsParse imports or use Pest arch()Custom rulesMust run in CI and not be disabled
CODEOWNERSModule owners review every change to their pathsSocial enforcementBottleneck if owners are few

Big-bang redesign ​

SolutionHowAdvantageCost / limitation
Strangler approachRoute one feature at a time to the new designAlways shippableTwo designs coexist for a while
Refactor behind testsCharacterisation tests, then refactoring movesSmall steps, reversibleNeeds test discipline
Monolith firstFowler: begin as a monolith, split by observed boundariesAvoids wrong boundariesA deployment unit that grows

Analysis paralysis ​

SolutionHowAdvantageCost / limitation
Timebox plus spikeOne day of prototype to answer the open questionReplaces opinion with evidenceSpike code must be thrown away
Decide the reversible fastUse the reversibility tableSaves meetings for expensive decisionsRequires honest rating
Last responsible momentDefer a decision until the cost of not deciding exceeds the cost of decidingLearn firstNeeds an interface so deferral is safe

Choosing: how much design, when ​

SituationArchitecture effortDesign effortArtifactsReason
Prototype for a demo, one developer, one weekNoneMinimalCode onlyWill be thrown away
New product, one team, unknown marketLow: modular monolith, one DBMedium: module boundaries, tests1-3 ADRs, READMEFowler's Monolith First
Established product, 3-5 teamsMedium: boundaries and data ownershipMediumADRs, module APIs, fitness testsTeams collide on shared code
Platform with external API clientsHigh: API contract, versioningHigh on public surfaceADRs, OpenAPI, deprecation policyReversal costs years
Safety or regulatory domainHigh: documented, reviewedHighFormal design documents, traceabilityAuditable evidence required
Legacy system under rescueTargeted: find boundaries with change couplingRefactor under testsMap of modules, debt listDo not redesign what you do not understand
Spiky, huge-scale workloadHigh: System DesignMediumCapacity estimates, ADRsLoad shapes structure

Decision flow for a single choice:

text
1  Is it expensive to reverse (more than one sprint, more than one team)?
2    yes -> write an ADR, prototype if unsure, review with owners
3    no  -> Does anyone else depend on it?
4            yes -> make it a public interface; version it
5            no  -> design inside the module, cover with tests, move on

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

Design and architecture meet most clearly when the same feature is deployed in different shapes. The decision stays the same at each step: where is the boundary and what crosses it?

Monolith: one process, one database ​

How it shows up: a single deployable; boundaries are folders, namespaces and packages. All calls are function calls; one BEGIN/COMMIT covers the order and its price snapshot.

Simplest correct usage: layered or feature-folder structure, one composition root, ADRs for the three biggest decisions, a README per module.

Example (simple): a blog: PostController → PublishPost action → posts table. The only architectural decision worth an ADR is the database.

Example (production-shaped): an online shop where checkout, pricing and fulfilment are folders. Pricing and orders share a transaction, so a quote and the order that used it are stored atomically.

Modular monolith and multiple databases ​

How it shows up: modules own their code and their tables; each exposes a facade; a fitness test forbids reaching into internals. This is the shape of this page's example and what Modular Monolith teaches in depth.

sql
-- PostgreSQL: one schema and one role per module (design decision made visible in the database).
CREATE SCHEMA ordering;  CREATE SCHEMA pricing;
CREATE ROLE ordering_app LOGIN;  CREATE ROLE pricing_app LOGIN;
GRANT USAGE, CREATE ON SCHEMA ordering TO ordering_app;
GRANT USAGE, CREATE ON SCHEMA pricing  TO pricing_app;
-- Ordering stores the quote it was given; it does not read pricing tables.
CREATE TABLE ordering.orders (
  id             bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  tier           text   NOT NULL,
  subtotal_cents bigint NOT NULL CHECK (subtotal_cents >= 0),
  discount_cents bigint NOT NULL CHECK (discount_cents >= 0),
  total_cents    bigint NOT NULL CHECK (total_cents = subtotal_cents - discount_cents),
  currency       char(3) NOT NULL
);

The CHECK constraints are design too: the rule "total = subtotal - discount" is stated where the database can enforce it, in PostgreSQL, MySQL (8.0.16 and later enforce CHECK; earlier versions parse and ignore it), SQL Server and Oracle alike.

Microservices: boundary with a network ​

What survives: the module boundary becomes a service boundary; the facade becomes an HTTP/gRPC API; the Pricer interface gets an HTTP client implementation.

What breaks: the shared transaction (use an outbox and idempotent consumers), latency (a quote is now a network call), partial failure (pricing down means checkout must degrade). Fowler's MicroservicePremium argument and Monolith First explain why this step needs a reason, such as an independent team or independent scaling; ADR-0007's "revisit if" clause is exactly that reason written down.

text
     Checkout flow after the split (ordering-svc, pricing-svc)
1    POST /orders                       ordering-svc receives the request
2    POST /quotes (timeout 200 ms)      ordering-svc -> pricing-svc
3    200 {subtotal, discount, total}    pricing-svc answers; ordering stores the quote it was given
4    INSERT orders                      ordering DB commit
5    publish OrderPlaced (outbox)       fulfilment, invoicing react asynchronously
     Failure path: step 2 times out -> retry once, then fall back to list price + flag for review

Only the adapter in cmd/shop/main.go (Go) or the container binding (Laravel) changes: that is what a good level-2 design buys.

Distributed data: replicas, caches and shared schemas ​

Where the design is testedWhat breaksDesign response
Quote cache in RedisStale quotes after a rule changeVersion the rules in the cache key; short TTL
Read replica for order historyReplica lag shows a missing orderRead-your-writes from the primary after checkout
Pricing rules shared by DB accessTwo writers, no ownerOne owning module; others use the API or events
Multi-region deploymentCross-region latency for every quoteReplicate rules read-only; keep quote computation local
Event schema changesOld consumers breakVersioned events (Message design)

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

ScaleStructureDesign practice
1× (one team, one app)Layered or feature folders, one DBKeep functions small and tested; one ADR for the DB
10× (several teams, one repo)Modular monolith, schema per moduleModule APIs, fitness tests, CODEOWNERS, ADR per boundary
100× (many teams, many deploys)Services per business capability, event streamsContracts as products, consumer-driven tests, system design capacity work

Lab: design a feature at three levels ​

You will run the example, break a boundary on purpose, change a rule, and write an ADR. Everything runs offline.

Setup.

bash
cd docs/snippets/design/architecture-vs-design/go
go vet ./...
go test ./...
go run ./shop/cmd/shop
# order 1: subtotal 12000, discount 1200, total 10800 EUR

Step 1: read the three levels. Open shop/arch_test.go (level 1), shop/pricing/pricing.go and shop/ordering/ordering.go (level 2), shop/pricing/internal/discount/discount.go (level 3). Expected: you can name, for each file, the one decision it records.

Step 2: break the boundary. Add this import to shop/ordering/ordering.go:

go
import _ "academy/architecture-vs-design/shop/pricing/internal/discount"

Run go build ./.... Expected: the compiler refuses, because internal/ is only importable from inside shop/pricing (Go 1.4 rule). Now import academy/architecture-vs-design/shop/pricing instead and run go test ./shop. Expected: TestOrderingDoesNotReachIntoPricing fails with ... imports academy/architecture-vs-design/shop/pricing (forbidden by architecture decision). Revert.

Step 3: change a rule at level 3. Change the gold rule to 15% off from 50 EUR (MinSubtotalCents: 5000, PercentOff: 15 in pricing.go). Expected: go run prints discount 1800, total 10200; only pricing.go changed; ordering and main.go untouched; the existing unit test in discount still passes because it builds its own Rules.

MeasureBefore (before/checkout.go)After (three levels)
Files touched by "change the discount"1 (and it also parses HTTP and writes SQL)1 (pricing.go)
Can the rule be tested without a database?NoYes (discount_test.go)
Can the boundary be broken silently?n/a (no boundary)No (compiler plus arch_test.go)
Where is the reason for the structure written?NowhereADR-0007

Step 4: write ADR-0008. Decide whether pricing should become a service when a second team takes it over. Use the template in Writing an ADR: context (what changed), decision (stay or split), consequences (what you give up). Expected: half a page, with a revisit trigger.

Step 5: measure your own project. Run this in any git repository to list the most frequently changed files (churn), the usual first suspects for a hidden boundary problem:

bash
git log --since='6 months ago' --name-only --pretty=format: | sort | uniq -c | sort -rn | head

Expected: a top-ten list of files; for each, ask which level of design it belongs to and whether more than one team edits it (see change coupling in SRP for the co-change version).

Step 6 (Laravel, optional). Copy the PHP files into a Laravel 13 project, add App\Modules\Pricing\PricingServiceProvider::class to bootstrap/providers.php, run ./vendor/bin/pest. Expected: the three arch expectations and the three DiscountRules tests pass; adding use App\Modules\Pricing\Internal\DiscountRules; to PlaceOrder.php makes the first arch test fail.

Common misconceptions ​

BeliefReality
Architecture is the diagramA diagram represents architecture; the decisions and structures are the architecture
Architects do not write codeFowler: architecture is shared understanding of the expert developers; architects who stop coding lose the feedback
Design is done before codingRoyce: design iterations are "never confined to the successive steps"; code feeds design
Agile means no designAgile principle: "Continuous attention to technical excellence and good design enhances agility"
Waterfall was invented as a recommendationRoyce called the simple version "risky" and "invites failure"
Low-level design is unimportantMoney rounding, idempotency and error handling live there
Cost of change grows exponentially, alwaysIt is a model; short feedback loops flatten it, and some decisions stay costly (database, public API)
More documentation is better designNygard: large documents are never kept up to date; use small ADRs
Microservices are an architecture; monoliths are notA modular monolith is an architecture with decisions, boundaries and tests
Technical debt is just bad codeDebt includes deliberate, prudent trade-offs with a payback plan; the metaphor is about interest on future changes
Design patterns are the designPatterns are mid-level vocabulary; architecture and module boundaries come first
Every decision needs an ADROnly architecturally significant ones; everything else belongs in code and tests

Cheat sheet ​

TopicRemember
Three levelsArchitectural, high-level, detailed (SWEBOK v4 stages)
Architecture (ISO 42010)Fundamental concepts or properties of a system in its environment, and the principles of its design and evolution
Architecture (Fowler)What is hard to change; the shared understanding of the experts
Architecture (Johnson)The important stuff, whatever that is
Intent (Martin)The structure should say what the system is for; defer frameworks and databases
Test for "architectural"Reversal is expensive or many teams depend on it
ADROne page per decision: context, decision, consequences, status; superseded, never deleted
ArtifactsADR, diagram, interface, prototype, tests, fitness test
Cost of changeA model; flatten it with tests, CI, refactoring, small interfaces
BDUF vs emergentA balance (Highsmith's scales); decide the expensive up front
Technical debtInterest is the extra effort on every feature; pay it with the next feature
Go toolsinternal/, small consumer-side interfaces, cmd/, go/parser fitness tests
Laravel toolsService providers, bind(), Actions, Pest arch(), bootstrap/providers.php
PathsSystem Design (load), Architecture (trade-offs), Design (responsibilities and change)
Reading order01 → 02 → 03 → 04 → 06 → SOLID → patterns → key issues

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 — Name the three stages of software design in SWEBOK v4 and give one decision for each. Important ​

Answer

Answer: Architectural design (monolith or services), high-level design (module interfaces), detailed design (algorithm, rounding rule, error type). See Levels of design.

2 — Why does SWEBOK v4 have a separate Architecture KA when the previous edition did not? Good to know ​

Answer

Answer: Because of "the significant interest and growth of the discipline since the 1990s". The Design KA keeps architectural design as its first stage and points to the Architecture KA. See History.

3 — State the IEEE 1471 definition and say what Fowler's definition adds. Good to know ​

Answer

Answer: IEEE 1471: "The fundamental organization of a system embodied in its components, their relationships to each other, and to the environment, and the principles guiding its design and evolution." Fowler adds a cost view ("things that people perceive as hard to change") and a social view (the shared understanding of the expert developers). See definitions.

4 — A decision takes two hours to reverse and affects one module. Does it need an ADR? Must-know ​

Answer

Answer: No. It is detailed design; code, tests and a pull request description are enough. See Reversibility.

5 — What did Royce write about the simple waterfall figure? Good to know ​

Answer

Answer: "I believe in this concept, but the implementation described above is risky and invites failure." He then showed iteration between phases. See History.

6 — What flattens the cost-of-change curve, according to Fowler? Important ​

Answer

Answer: Testing and continuous integration at the core, plus disciplined refactoring; the common factor is a short feedback loop. See The cost-of-change curve.

7 — Why is the cost-of-change curve not a law? Important ​

Answer

Answer: The flat curve was introduced as a metaphor with anecdotal evidence; real curves depend on practices and on the kind of decision (database engine and public APIs stay costly). The diagram here is illustrative.

8 — In the example, why does ordering own the Pricer interface in Go? Important ​

Answer

Answer: Consumer-side interfaces mean the consumer does not import the provider, so there is no compile-time dependency from ordering to pricing; an adapter in the composition root connects them. See The Go angle.

9 — Give two ways to enforce an architecture decision automatically. Important ​

Answer

Answer: A language mechanism (Go internal/) and a fitness test (arch_test.go parsing imports, Pest arch() with not->toUse). See Solving: boundary erosion.

10 — How is technical debt related to design? Must-know ​

Answer

Answer: The structure no longer matches what the team needs; each feature pays "interest" in extra effort (Fowler's four versus six days). SWEBOK v4 also names architectural technical debt. See Technical debt.

11 — Which path would you read to estimate Black Friday traffic for the pricing module? Good to know ​

Answer

Answer: The System Design path (capacity and scaling), then return to Design for how the module is shaped. See Neighbouring paths.

Glossary ​

TermMeaning
Software designThe discipline, processes, result and life-cycle stage of structuring software (SWEBOK v4's four senses)
Software architectureFundamental concepts or properties of a system in its environment, embodied in elements, relationships and design principles
Architectural designThe widest design stage: whole system and its environment
High-level designOutward-facing design: components, interfaces, interactions
Detailed designInward-facing design: internal structure of each component
SWEBOKGuide to the Software Engineering Body of Knowledge (IEEE Computer Society; V4 published October 2024)
IEEE 14712000 recommended practice for architecture description; superseded by ISO/IEC/IEEE 42010
ISO/IEC/IEEE 42010The international standard for architecture description
SDDSoftware design description: a representation of the design used for communication
ADRArchitecture decision record: one short file per significant decision
Architecturally significantAffects structure, non-functional characteristics, dependencies, interfaces or construction techniques (Nygard)
Fitness test / functionAn automated check that an architectural rule still holds
FacadeA single public entry point to a module that hides its internals
Composition rootThe one place where modules are instantiated and wired together
Information hidingParnas: each module hides a design decision likely to change
CouplingHow much a change in one module forces a change in another
CohesionHow strongly the parts of a module belong together
Cost of change curveA model of how expensive a change is as the project progresses
BDUFBig design up front: most design is done before coding
Emergent / evolutionary designDesign that grows with code, protected by tests and refactoring
YAGNI"You Aren't Gonna Need It": do not build for speculative needs
Technical debtCunningham's metaphor: internal-quality shortfall whose "interest" is the extra effort on every future change
Modular monolithOne deployable organised into modules with enforced boundaries
Walking skeletonA thin end-to-end slice that exercises every level of the design
SpikeA time-boxed experiment to answer one design question
CRC cardsClass-Responsibility-Collaborator cards, a paper technique for object design
C4 modelA set of context, container, component and code diagrams (Simon Brown)

References ​

Built by Morteza Negahi