The Design Process: Conceptual Design, CRC Cards, Technical Design & Compromise
"We will never find a process that allows us to design software in a perfectly rational way. The good news is that we can fake it." — David L. Parnas and Paul C. Clements, A Rational Design Process: How and Why to Fake It
Summary: Design is a loop, not a staircase: find out what people need, decide what the pieces are and who does what (conceptual design), then decide how each piece is built (technical design), test your doubts with cheap experiments, and write down what you learned. CRC cards and GRASP are the tools that turn the first half into code. Focus: Eliciting requirements, conceptual versus technical design, CRC cards and how to run a session, role play, GRASP responsibility assignment, compromise and satisficing, spikes and prototypes, design reviews, design docs, RFCs and ADRs, a full library-lending example in Go and Laravel, and how the same process looks for a monolith and for microservices. Learning goal: Take a vague request, produce a glossary, a handful of CRC cards and a set of scenarios, assign responsibilities with GRASP, and turn the result into Go packages and Laravel modules, while knowing which decisions to postpone, which to record and which to test with a spike.
This page is the complete reference for how design work is actually done between "somebody wants a feature" and "somebody opens a pull request". It does not re-teach its neighbours: the difference between architecture and design is on Software Architecture vs Software Design, the quality attributes you trade against each other are on Quality Attributes, Functional & Non-Functional Requirements, the object-oriented vocabulary is on Object-Oriented Modeling, diagrams that show the result are on UML in Practice, coupling and cohesion as measurements are on Design Quality, the class-level result is on Low-Level Design, and the principles that check your cards are the SOLID chapters (start with SRP and DIP). The decision-record habit is deepened in Architecture Decisions & Trade-offs; the shared-language habit in Ubiquitous Language.
Page map
| If you are looking for | Go to |
|---|---|
| The whole process in a few tables | Everything in one minute |
| Why a design process exists and what it costs | Why a design process exists |
| Parnas, Simon, Beck and Cunningham, Larman, Nygard | Where it comes from |
| Requirements, conceptual design, technical design | Elicitation, Conceptual design, Technical design |
| CRC cards: anatomy, collaborators, role play | CRC card, Running a CRC session |
| Domain model first pass, glossary, ubiquitous language | Domain model first pass |
| GRASP: expert, creator, controller, coupling, cohesion, polymorphism, fabrication, indirection, variations | GRASP |
| Compromise, trade-offs, satisficing | Compromise |
| Spikes, prototypes, iteration | Iteration and spikes, Prototyping |
| Reviews, design docs, RFCs, ADRs | Design review, Documents that stay useful |
| Failure modes: database first, skipped conceptual design, gold plating | Failure modes |
| A full example from user stories to Go packages and Laravel modules | Worked example, Go, Laravel |
| Monolith versus microservices | In architecture |
| Hands-on experiments | Lab |
| Wrong beliefs, cheat sheet, self-check, every term | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The phases. Every row is unpacked in the concepts section.
| Phase | Question it answers | Typical artefact | Who is in the room | What goes wrong if skipped |
|---|---|---|---|---|
| Elicit requirements | What do people need, and what must not break? | User stories, acceptance criteria, glossary, constraints | Users, product, developers | You build the wrong thing well |
| Conceptual design | What are the parts, who knows what, who asks whom? | Mockups, conceptual model, CRC cards, scenarios | Developers plus domain experts | Code mirrors the database or the UI by accident |
| Technical design | How is each part built? | Classes, interfaces, data model, algorithms, package layout | Developers | Fine concepts, hard-to-change code |
| Spike / prototype | Will this risky idea work? | Throwaway code and a written answer | One or two developers | Weeks spent on an idea that cannot work |
| Review and record | Is it right, and will we remember why? | Design doc, RFC, ADR | Peers, owners | The same debate every six months |
The CRC card.
| Part | Rule | Example (Loan) |
|---|---|---|
| Class name | One singular noun from the glossary | Loan |
| Responsibilities | A handful of short verb phrases: what it knows or does | know due date; say if overdue; renew itself |
| Collaborators | The cards it must ask for help | Member, Copy |
| Size limit | One 4 by 6 inch index card (Beck and Cunningham) | If it does not fit, split the class |
The nine GRASP principles. Larman's mental toolset for assigning a responsibility.
| Principle | One-line rule | Where it landed in the example |
|---|---|---|
| Information Expert | Give it to the class that has the data | Loan.DaysLate |
| Creator | The class that records or contains B creates B | Ledger creates Loan |
| Controller | A non-UI class receives each system operation | lending.Service, CheckOutBook |
| Low Coupling | Prefer the option with fewer dependencies | Shelf, Members ports |
| High Cohesion | Keep a class about one topic | One package per concept |
| Polymorphism | Vary by type with polymorphic calls, not branches | FeePolicy |
| Pure Fabrication | Invent a class with no domain name when it helps | Clock, repositories |
| Indirection | Put a go-between to decouple two things | Adapters in the composition root |
| Protected Variations | Wrap the point of instability in an interface | Fee rules, shelf storage |
The failure modes.
| Failure | Symptom | Cure |
|---|---|---|
| Database first | Entities are tables, behaviour lives in controllers | Do cards and scenarios before the schema |
| Skipped conceptual design | The first design is the first code that compiled | One hour of cards before the first class |
| Gold plating | Features and flexibility nobody asked for | Scenarios drive cards; YAGNI |
| Analysis paralysis | Diagrams, no running code | Time-box, then spike |
| Big design up front | A frozen plan that reality contradicts | Small increments, revisit often |
Why a design process exists
Code is cheap to type and expensive to change. A process exists to move the expensive mistakes to the cheap moment: a card on a table costs seconds to rip up, a table in production costs a migration, an outage and a meeting. Parnas and Clements list the reasons why no project ever follows an ideal order (people who ask for software "do not know exactly what they want and are unable to tell us all that they know", facts appear during implementation, humans cannot hold all details in their heads) and still conclude that following the ideal process as closely as possible beats improvising.
| Improvise | Follow a loop |
|---|---|
| Fast first week | Slower first week (an hour or two of cards, a glossary) |
| Design emerges from whatever compiled first | Design is chosen between alternatives you wrote down |
| Reasons live in one person's head | Reasons live in a design doc or ADR |
| Surprises arrive in code review or production | Surprises arrive in a spike or a card session |
| Risk: rewrite | Risk: over-planning, documents nobody reads |
The picture is the loop this page teaches: five steps that you walk forward, with two feedback arrows. A spike (step 4) can send you back to technical design (step 3); anything you learn while building or reviewing can send you back to the requirements.
The analogy we reuse on this page: planning a house. First you ask the family what they need (three bedrooms, a quiet study, a wheelchair-friendly door). Then you draw a sketch with rooms and who walks through which door (conceptual). Then the engineer decides beam sizes, wiring and pipes (technical). If nobody is sure the soil can carry the extension, you dig a test hole (spike) instead of arguing. A neighbour or inspector reviews the plan (review), and the file with the reasons for the odd choices is what the next owner will thank you for (design doc). Pouring the concrete before the sketch is what "database first" means.
Three common misunderstandings, up front
- "A design process means big design up front." No. Beck and Cunningham stress creating objects "not to meet mythical future needs, but only under the demands of the moment". A good process designs one story at a time and revisits.
- "Design is drawing UML." Diagrams are one way to record a design. The design itself is the set of decisions: who knows what, who may call whom, what changes together. CRC cards deliberately contain no syntax.
- "If we are agile we do not need design." Agile teams design every day, in smaller pieces and with more feedback; XP even gives design its own practice (simple design, CRC cards, spikes).
Where it comes from
Parnas and Clements, 1986. A Rational Design Process: How and Why to Fake It argues that the ideal "top down" process is unreachable but useful. Their reasons the real process is never rational include that clients cannot state everything they want, that some facts "only become known to us as we progress in the implementation", and that "human errors can only be avoided if one can avoid the use of humans". Their advice:
"If we have identified an ideal process but cannot follow it completely, we can still follow it as closely as possible and we can write the documentation that we would have produced if we had followed the ideal process." — Parnas and Clements, A Rational Design Process: How and Why to Fake It
The paper also tells you what to keep: "We make a policy of recording all of the design alternatives that we considered and rejected." That sentence is the ancestor of the ADR. (We read the PDF hosted in a Tufts course archive; venue and date come from the Crossref record: IEEE Transactions on Software Engineering, vol. SE-12, no. 2, February 1986, pp. 251-257.)
Simon, 1956. Herbert Simon introduced satisficing, the idea that decision makers search "until an acceptability threshold is met" instead of maximising (we read Wikipedia's summary, a secondary source, and the citation to Simon's 1956 Psychological Review paper). Design compromise is satisficing with named criteria.
Beck and Cunningham, 1989. At OOPSLA '89 (New Orleans, 1 to 6 October 1989) Kent Beck and Ward Cunningham presented A Laboratory for Teaching Object-Oriented Thinking:
"We introduce CRC cards, which characterize objects by class name, responsibilities, and collaborators, as a way of giving learners a direct experience of objects." — Beck and Cunningham, OOPSLA '89
They say Cunningham invented the cards "in response to a need to document collaborative design decisions", first as a HyperCard stack, then on 4 by 6 inch index cards. Their reference list points to Wirfs-Brock and Wilkerson's responsibility-driven design as a parallel line of work.
Wirfs-Brock, 1989 onward. Object-Oriented Design: a Responsibility-Driven Approach (Wirfs-Brock and Wilkerson, OOPSLA '89; we only read its citation in Beck and Cunningham) is the origin of treating design as assigning responsibilities to roles.
Larman, 1997 to 2004. Craig Larman's Applying UML and Patterns names GRASP, "nine fundamental principles in object design and responsibility assignment" (Wikipedia's wording, a secondary source; Wikipedia marks the 1997 date as needing a citation, so cite the 2nd and 3rd editions, 2001 and 2004). Larman is quoted there as saying "the critical design tool for software development is a mind well educated in design principles. It is not UML or any other technology."
Evans, 2003, and the ubiquitous language. Fowler's bliki describes it as "the practice of building up a common, rigorous language between developers and users". It is where a design process meets domain-driven design.
Wells, 1999. ExtremeProgramming.org's spike rule: "Create spike solutions to figure out answers to tough technical or design problems."
Nygard, 2011. Documenting Architecture Decisions (15 November 2011) proposes keeping "a collection of records for 'architecturally significant' decisions".
Google's design docs, Rust RFCs. Two public, checkable examples of design documents at scale; see In production systems.
The concepts, one by one
Each block follows the same order: plain words, the usual wrong belief, a precise definition, a timeline, real scenarios, what to do about it.
Eliciting requirements Must-know
In plain words: find out what people need and what would make them unhappy, before deciding anything about classes or tables.
Common misunderstanding: "The requirements are the feature request." A request is a solution someone already chose ("add a button that exports CSV"). Elicitation digs to the need ("the accountant has to reconcile loans monthly").
Definition: the activity of discovering, stating and agreeing functional requirements (what the system does), non-functional requirements (how well; see Quality Attributes) and constraints (budget, law, existing systems). For a design process, the useful outputs are small: user stories with acceptance criteria, a list of constraints, and a first glossary.
Source What they said What the need is Artefact
1 Member "I want to borrow a book" take one physical copy home for 14 days story + acceptance criteria
2 Librarian "Show me overdue books" chase late returns daily story + report scenario
3 Treasurer "Fines must stop at 10.00" cap on per-loan fee constraint, becomes FeePolicy cap
4 Branch manager "Children get 3 books at most" limit varies by member category rule that varies, becomes Member.LoanLimit
5 all four "book" Title (the work) vs Copy (the item) glossary entryReal scenario: a library app where "book" means the title for the searcher and the physical copy for the librarian; a payments feature where "refund" means a bank reversal to finance and a store credit to support; an HR system where "employee" includes contractors for access control but not for payroll.
Fix: write each need as a user story ("As a member I can renew a loan once so that I keep a book I have not finished"), add two or three acceptance criteria ("a second renewal is refused", "renewal is refused when another member waits"), and put every contested noun into the glossary. Link out to Requirements to Architecture for the architectural drivers.
Conceptual design Must-know
In plain words: decide what the parts are and who is responsible for what, in the language of the problem, ignoring databases, frameworks and screens' pixels.
Common misunderstanding: "Conceptual design is a diagram you draw once to please a manager." It is the cheapest place to find a wrong decomposition, so it is where most of the thinking should happen, with domain experts in the room.
Definition: the design activity that produces four things: (1) mockups of the key screens or outputs, to confirm the need with users; (2) a conceptual model of the domain: the nouns, their meanings and relationships (the glossary plus a sketch); (3) responsibilities: what each concept knows and does; (4) collaborations: which concepts ask which. CRC cards capture 2 to 4 together.
Step Input Output
1 1 user stories glossary: Title, Copy, Member, Loan, Reservation, Fee
2 2 glossary + stories CRC cards, one per concept
3 3 story "check out a copy" scenario walk: Member -> Lending -> Copy, Loan
4 4 walk exposes a gap new responsibility: "Loan says if overdue"
5 5 all scenarios pass conceptual design done enough to start technical designReal scenario: a food-ordering app where the team agrees that an Order is created when payment is authorised, not when the cart is submitted; a booking system where the conceptual model separates Reservation (a promise) from Stay (a fact).
Fix: keep it informal and visual (index cards, whiteboard, paper mockups), run two or three scenarios, stop when the scenarios pass. The deliverable is shared understanding, not a document.
Technical design Must-know
In plain words: decide how each part will be built with the tools you really have.
Common misunderstanding: "Technical design is the same as the class diagram." A class diagram is one view. Technical design also covers data storage and shape, algorithms, error handling, concurrency, interfaces between modules, deployment and testing.
Definition: the design activity that turns conceptual cards into classes, interfaces, data structures, algorithms and a package or module layout, constrained by the language, framework, database and quality attributes. It is where Go packages and Laravel modules get their names.
Card / concept Technical decision Go Laravel
1 Loan immutable value, renew returns a new one type Loan struct final readonly class Loan
2 Lending one entry point per system operation lending.Service CheckOutBook action
3 FeePolicy interface with two implementations interface + structs interface + readonly classes
4 Copy availability atomic compare-and-set, no read-then-write Catalog.Take under mutex UPDATE ... WHERE on_shelf
5 Loans storage table with due_at index, ids not foreign keys sql / repository migration with ulid + indexReal scenario: choosing a compare-and-set UPDATE instead of "read the flag, then write it" so two members cannot take the same copy; choosing due_at as an indexed column because the librarian's overdue report filters on it.
Fix: use the cards as the checklist. For each responsibility ask: which type or function, which data, which failure, which test? See Low-Level Design and Data Persistence in Design.
The CRC card Must-know
In plain words: one index card per concept: its name, a few things it knows or does, and the other cards it needs help from.
Common misunderstanding: "A CRC card is a tiny class diagram." No. Beck and Cunningham wrote that CRC cards "place the designer's focus on the motivation for collaboration by representing (potentially) many messages as a phrase of English text". There are no types, no method signatures, no inheritance arrows. Its power comes from being too small for detail.
Definition: a CRC card has three parts. The class name "creates a vocabulary for discussing a design". Responsibilities "identify problems to be solved" and are "a handful of short verb phrases, each containing an active verb". Collaborators are "objects which will send or be sent messages in the course of satisfying responsibilities"; and "Collaboration is not necessarily a symmetric relation". Ambler's gloss: a responsibility is "anything that a class knows or does", and a collaboration takes "one of two forms: A request for information or a request to do something".
Card: Loan | Collaborators
1 know due date | Member
2 say if overdue | Copy
3 renew itself (once) |
4 compute days late |
--------------------------------------------------------------
Reading the card aloud: "I am a Loan. I know when I am due. I ask Copy which item I am for
and Member which category I belong to. Nobody asks me to print an invoice."Real scenario: the ATM exercise in the original paper ("the objects in an automatic banking machine", a device-driver object, a central-bank object, a user-interface object); an order-fulfilment team that discovers that nobody owns "reserve stock" until they act out a purchase with cards.
Fix: if you cannot name a card with a singular noun from the glossary, it is not a concept yet. If a card has more than about six responsibilities (a smell threshold, not a law), split it. If a responsibility is not a verb phrase, rewrite it. The Go snippet below checks these rules mechanically:
// A CRC session written down as data, plus the mechanical checks a facilitator
// does by eye: every collaborator has a card, no card is overloaded, no card is alone.
package main
import (
"fmt"
"os"
"sort"
)
// Card is one index card: a class name, short verb-phrase responsibilities,
// and the cards it has to ask for help.
type Card struct {
Class string
Responsibilities []string
Collaborators []string
}
const maxResponsibilities = 6 // a smell threshold, not a law
func check(cards []Card) []string {
known := map[string]bool{}
for _, c := range cards {
known[c.Class] = true
}
touched := map[string]bool{}
var problems []string
for _, c := range cards {
if len(c.Responsibilities) > maxResponsibilities {
problems = append(problems, fmt.Sprintf("%s has %d responsibilities: split the card", c.Class, len(c.Responsibilities)))
}
if len(c.Responsibilities) == 0 {
problems = append(problems, fmt.Sprintf("%s has no responsibility: it is a data holder or a noun nobody needs", c.Class))
}
for _, other := range c.Collaborators {
if !known[other] {
problems = append(problems, fmt.Sprintf("%s collaborates with %q, which has no card", c.Class, other))
continue
}
touched[c.Class] = true
touched[other] = true
}
}
for _, c := range cards {
if !touched[c.Class] {
problems = append(problems, fmt.Sprintf("%s collaborates with nobody: out of scope or missing a scenario", c.Class))
}
}
sort.Strings(problems)
return problems
}
func main() {
cards := []Card{
{"Member", []string{"know own category", "know own loan limit"}, nil},
{"Copy", []string{"know own barcode", "know if it is on the shelf", "be taken", "be put back"}, nil},
{"Title", []string{"know ISBN, name, author", "match a search query"}, []string{"Copy"}},
{"Loan", []string{"know due date", "say if it is overdue", "renew itself", "compute days late"}, []string{"Copy", "Member"}},
{"Ledger", []string{"record loans", "count open loans of a member", "create a Loan"}, []string{"Loan"}},
{"Lending", []string{"check out a copy", "renew a loan", "accept a return", "list overdue loans"}, []string{"Member", "Copy", "Loan", "Ledger", "FeePolicy", "Reservation"}},
{"FeePolicy", []string{"turn days late into a fee"}, nil},
{"Reservation", []string{"know who waits for which title", "tell Lending a copy is wanted"}, []string{"Member", "Title"}},
}
problems := check(cards)
for _, p := range problems {
fmt.Println("CRC:", p)
}
if len(problems) > 0 {
os.Exit(1)
}
fmt.Println("CRC: all cards consistent")
}Running a CRC session (role play) Must-know
In plain words: a small group sits around a table, writes cards, then acts out a scenario: each person holds a card and says what that class would do and whom it would ask.
Common misunderstanding: "The cards are the deliverable." Beck and Cunningham report a case where finished cards were delivered to a client as design documentation and "the recipient was unable to make sense of the cards out of context". The session is the deliverable; the cards are props. Their other observation: "We were surprised at the value of physically moving the cards around."
Definition: the procedure, from the paper: "We start with only one or two obvious cards and start playing 'what-if'. If the situation calls for a responsibility not already covered by one of the objects we either add the responsibility to one of the objects, or create a new object to address that responsibility." Design "tends to progress from knowns to unknowns, as opposed to top-down or bottom up".
Who Says (scenario: Member M-7 checks out copy C-1, limit is 5)
1 Facilitator "Scenario 1. M-7 scans C-1 at the desk."
2 Lending "I am asked to check out. I need M-7's limit: Member, what is it?"
3 Member "Adult, limit 5."
4 Lending "Loan, how many are open for M-7?" -- nobody has that card.
5 Group "Loan knows its own dates, but counting a member's loans is a question about ALL loans."
6 Group decision: new card Ledger: records loans, counts open loans, creates a Loan (Creator).
7 Lending "Copy, are you on the shelf? Take yourself." Copy: "Yes. Done."
8 Lending "Ledger, open a Loan for M-7 and C-1." Ledger: "L0001, due in 14 days."| Step in a session | What you do | Typical time | Rule of thumb |
|---|---|---|---|
| Prepare | Pick one story, bring the glossary, index cards, pens | 10 min | One story or one use case per session (Ambler: "Model in Small Increments") |
| Find classes | Write 3 to 5 obvious cards from the glossary | 10 min | Singular nouns only |
| Find responsibilities | Verb phrases under each name | 10 min | "Knows" and "does" |
| Define collaborators | For each responsibility ask "can this class do it alone?" | 10 min | If not, who can? |
| Role play | One person per card, walk the scenario aloud | 20 min | Pick up the card you play |
| Move cards | Cards that talk a lot sit close | continuous | Parts below the whole |
| Decide and record | Photograph the table, note the decisions and open questions | 10 min | Record the decision, not the pile of cards |
Real scenario: a three-person team plus the librarian at one table; when the librarian says "we never lend a reference copy" the group adds a responsibility to Copy ("know if lendable") that no developer would have guessed.
Fix: use roles: a facilitator who keeps to one scenario, a scribe who writes decisions, and a "devil's advocate" who invents awkward scenarios. Keep stakeholders in the room. Stop when two or three scenarios pass without new cards.
Responsibility and collaborator Important
In plain words: a responsibility is something a card is accountable for; a collaborator is a card it must ask because it cannot do that alone.
Common misunderstanding: "A responsibility is a method." A responsibility is an obligation phrased in problem words ("know if I am overdue"); it may become one method, several, or a field. Ambler adds a rule worth remembering: "A class is able to change the values of the things it knows, but it is unable to change the values of what other classes know."
Definition: a responsibility is a knowing or doing obligation of a role. A collaborator is another role whose services this one needs to fulfil it. Two kinds of collaboration exist: asking for information and asking for action. Asymmetry is normal: Loan asks Copy; Copy never asks Loan.
Responsibility on card Can the card do it alone? Collaborator Kind
1 Loan: know due date yes - -
2 Loan: compute days late yes (due date + "now") Clock (given in) information
3 Lending: check out a copy no Member, Copy, Ledger information + action
4 Copy: be taken yes - -
5 Ledger: count open loans for member yes (it holds the loans) - -Real scenario: a Cart card that "knows its lines" and "knows its total" but is asked by Checkout to "apply a discount"; the discount rule belongs to PricingPolicy, so Checkout collaborates with PricingPolicy, not with the cart's internals.
Fix: write each responsibility so that you could answer "who changes this?"; if two actors change it, split (SRP).
Compromise, trade-offs and satisficing Must-know
In plain words: you cannot have everything. Making a design means picking which qualities to favour and writing down what you gave up.
Common misunderstanding: "A good design maximises every quality." Quality attributes pull against each other, so the target is "good enough on the ones that matter", which is Simon's satisficing: search "until an acceptability threshold is met, without necessarily maximizing any specific objective".
Definition: design compromise is the explicit choice between options whose benefits conflict, judged against the quality attributes you ranked in the requirements. Satisficing means stating the threshold first ("search answers in under 300 ms for 100,000 titles"), taking the first option that meets it, and moving on.
| Quality you push up | Usually costs | Example in the library system |
|---|---|---|
| Performance | Simplicity, sometimes consistency | Caching search results makes "available now" possibly stale |
| Consistency | Availability, latency | Strong consistency on copy checkout, a lock or compare-and-set per copy |
| Flexibility | Simplicity, performance | FeePolicy interface: one more indirection for easy rule changes |
| Simplicity | Flexibility | Hard-code one fee rule until a second appears |
| Security | Usability, speed | Re-authenticating members for each renewal |
| Time to market | Test depth, polish | Ship checkout and returns first, reservations later |
| Cost | Redundancy, resilience | One database, one region |
Option Meets "overdue list under 1 s at 100k loans"? Cost Decision
1 full scan, no index yes (measured: ~0.1 ms in memory) none satisfices; start here
2 index on due_at yes one migration adopt when the scan is measured slow
3 materialised overdue table yes sync logic, staleness rejected: no need yet
4 search service yes a new moving part rejected, recorded in the ADRReal scenario: choosing to put loans and copies in one database now ("one transaction for checkout") while recording that a split would need a saga; deciding that "available now" in search may be a minute old.
Fix: rank the top three quality attributes before the session, state a threshold per option, record rejected alternatives with the reason in the design doc or an ADR. Use Architecture Decisions & Trade-offs for the longer method.
Iterative design and spikes Important
In plain words: design in small rounds. When a round hits a doubt that talking cannot settle, write a small throwaway program to answer that one question.
Common misunderstanding: "A spike is a first version." A spike answers a question; it is not a first version. XP says it plainly: "Most spikes are not good enough to keep, so expect to throw it away." The goal, in XP's words, is "reducing the risk of a technical problem", and also improving the reliability of a story's estimate.
Definition: a spike is a time-boxed experiment, ignoring every concern except the question. Related terms: a tracer bullet (a thin end-to-end slice that you keep and grow) and a walking skeleton (the smallest deployable end-to-end system). A spike is deleted; a tracer bullet is built on.
Day Activity Output
1 D1 Round 1: cards for "check out" and "return" 6 cards, 2 scenarios pass
2 D1 Doubt: "can we scan all open loans for overdue?" question written down, 30 min time box
3 D1 Spike: 1M random loans, scan, count about 1 ms on a laptop (see snippet)
4 D2 Answer recorded in the design doc "scan is fine; the cost is the DB round trip"
5 D2 Spike file deleted; round 2: reservations new cards// SPIKE (throwaway). Question: can we find overdue loans by scanning all open
// loans on each librarian page view, or do we need a due-date index?
// Time box: 30 minutes. Answer is written in the design doc; this file is deleted.
package main
import (
"fmt"
"math/rand"
"time"
)
type loan struct {
id int
due time.Time
}
func main() {
now := time.Now()
rng := rand.New(rand.NewSource(1))
for _, n := range []int{10_000, 100_000, 1_000_000} {
loans := make([]loan, n)
for i := range loans {
loans[i] = loan{i, now.Add(time.Duration(rng.Intn(60)-30) * 24 * time.Hour)}
}
start := time.Now()
overdue := 0
for _, l := range loans {
if l.due.Before(now) {
overdue++
}
}
fmt.Printf("%9d open loans: scan %v, %d overdue\n", n, time.Since(start), overdue)
}
// Reading of the result: a full scan is cheap for a branch library
// (tens of thousands of loans). The real cost is a database round trip,
// so the design question moves to the query, not to an in-memory index.
}Real scenario: checking whether a PDF library renders 200 pages in under 2 seconds; whether SELECT ... FOR UPDATE SKIP LOCKED is enough for a work queue before choosing a broker; whether a third-party API rate limit fits the planned batch size.
Fix: write the question and the time box at the top of the file, write the answer in the design doc, delete the code. If the code is worth keeping, rewrite it with tests.
Prototyping: throwaway versus evolutionary Important
In plain words: a prototype is something you can show or run before the real system exists. Either you throw it away, or you keep growing it. Decide which before you start.
Common misunderstanding: "We will clean the prototype up later." Prototypes built for speed ignore structure on purpose; Wikipedia's summary of the literature notes that for throwaway prototypes "issues of evolvability, maintainability, and software structure" are ignored. The temptation to ship it anyway is the classic failure.
Definition: throwaway (rapid, close-ended) prototyping builds "a model that will eventually be discarded rather than becoming part of the final delivered software". Evolutionary prototyping builds the first version of the real system and refines it. (We read Wikipedia's Software prototyping page, a secondary source.)
| Kind | Purpose | Quality bar | Kept? | Good for |
|---|---|---|---|---|
| Paper or clickable mockup | Confirm the need and the flow | Low | No | Screens, forms, reports |
| Throwaway code prototype | Learn whether an idea works | Low | No | Risky algorithm, integration |
| Spike | Answer one technical question | Lowest | No | Estimation risk |
| Tracer bullet / walking skeleton | Prove the architecture end to end | Real | Yes | New system |
| Evolutionary prototype | Reach a releasable version with feedback | Real, growing | Yes | Unclear requirements, friendly users |
Real scenario: a clickable mockup of the librarian's overdue screen shown to two librarians on day one; a walking skeleton that checks out one copy through HTTP, Go service, database and a Slack notification.
Fix: label the prototype in the repository (spike/, prototype/), state "delete after YYYY-MM-DD" in its first line, and make the decision to keep it an explicit rewrite.
Design review Important
In plain words: before building, let someone else poke holes in the design while changing it is still cheap.
Common misunderstanding: "A review checks the author's work for mistakes." It also spreads knowledge and builds consensus. The Google design-doc essay lists the functions: early identification of design issues "when making changes is still cheap", "achieving consensus", "ensuring consideration of cross-cutting concerns", and forming "the basis of an organizational memory around design decisions".
Definition: a structured examination of a design artefact (cards, doc, RFC) by people who did not write it, against explicit criteria: requirements met, quality attributes, risks, alternatives, operations (monitoring, migration), security, cost.
| Review question | What it catches |
|---|---|
| Which requirement does each card or component serve? | Gold plating |
| What are the non-goals? | Scope creep |
| What would change together, and is it in one place? | SRP and cohesion problems |
| What breaks if component X fails or is slow? | Missing fault handling |
| How do we migrate and roll back? | One-way doors |
| Which alternatives were considered and why rejected? | Unexamined first idea |
| Who owns it at 3 a.m.? | Missing operations |
Step Who Action
1 1 author shares the doc with the team that knows the problem space
2 2 reviewers comment: questions, risks, alternatives; mark blocking vs non-blocking
3 3 author revises; unresolved disagreements go to a decision owner
4 4 decision owner approves with ADR status "accepted" or sends back
5 5 author links the doc from the implementation tickets and updates it when reality changesReal scenario: a payments change reviewed by the platform team and finance before code; a schema change reviewed for lock behaviour and rollback.
Fix: keep the criteria on a checklist, review the design (not the writer), and time-box rounds. Say clearly which comments block.
Design documents that stay useful Important
In plain words: write down the problem, the choice, and why, in a short text people can still find and trust next year.
Common misunderstanding: "More documentation is better documentation." Parnas and Clements blame "poor organisation" ("stream of consciousness" and "stream of execution" writing, where readers cannot find what they seek) and "boring prose" that repeats facts; their cure is documents that are organised for lookup and "produced with care". Google's essay is direct: "Writing design docs is overhead", so write one when the solution is ambiguous, not for obvious changes.
Definition: three lightweight forms.
| Document | Scope | Typical length | Key sections | Primary source |
|---|---|---|---|---|
| Design doc | One project or system | 1 to 3 pages ("mini design doc") up to about 10 to 20 for a larger project (Google) | Context and scope, goals and non-goals, the design, alternatives considered, cross-cutting concerns | Google "Design Docs at Google" |
| RFC | A proposal for change that needs wide comment | A few pages | Summary, motivation, guide-level explanation, reference-level explanation, drawbacks, rationale and alternatives, prior art, unresolved questions | Rust RFC template |
| ADR | One architecturally significant decision | One page | Title, context, decision, status, consequences | Nygard 2011 |
The Google essay's useful rule about non-goals: "non-goals aren't negated goals like 'The system shouldn't crash', but rather things that could reasonably be goals, but are explicitly chosen not to be goals." And on alternatives: "this section is one of the most important ones as it shows very explicitly why the selected solution is the best given the project goals".
An ADR in the Nygard form, filled for our example:
Title: 3. Loans and copies share one database for now
Status: accepted (2026-11-25)
Context: Checkout must never give one copy to two members. We have one team and one deploy.
Decision: Lending and Catalog use one PostgreSQL database; checkout takes a copy with a single
atomic UPDATE ... WHERE on_shelf. Modules talk through public APIs, not each other's tables.
Consequences: + one local transaction, no saga. - a split later needs an outbox and a saga.
Revisit when two teams own the modules or when read load needs separate scaling.Nygard's own rule for scope: keep records for "architecturally significant" decisions, "those that affect the structure, non-functional characteristics, dependencies, interfaces, or construction techniques", in the repository next to the code. See Architecture Decisions & Trade-offs.
Real scenario: a new engineer asks why checkout uses UPDATE ... WHERE on_shelf and not a lock; the ADR answers in one minute.
Fix: keep documents in the repository, date them, mark status (proposed, accepted, superseded), supersede rather than edit, link them from code comments and pull requests.
Domain model first pass and the glossary Important
In plain words: list the nouns of the problem, say what each one means in one sentence, and sketch which ones relate. That list is also the vocabulary of your code.
Common misunderstanding: "The domain model is the database schema." A schema stores data; a domain model also says what concepts do. Starting from tables makes everything look like data holders (Anemic vs Rich Models).
Definition: a first-pass domain model is the glossary plus a sketch of relationships and a few rules, stable enough to name cards. The glossary feeds the ubiquitous language: in Fowler's words (describing Evans) "building up a common, rigorous language between developers and users", which "should be based on the Domain Model used in the software". Class names on cards, package names in Go and module names in Laravel should come from this list.
| Term | Meaning (one sentence) | Not to be confused with |
|---|---|---|
| Title | A work identified by ISBN | Copy |
| Copy | One physical item with a barcode | Title |
| Member | A person with a card, category and limit | User account |
| Loan | A copy lent to a member until a due date | Reservation |
| Reservation | A promise that a title will be held for a member | Loan |
| Fee | Money owed for late return | Fine for lost item (not modelled) |
| Overdue | A loan that is open and past its due date | Late (a returned loan was late) |
Glossary conflict Resolution Where it shows in code
1 "book" = work or item? split into Title and Copy catalog.Title, catalog.Copy
2 "late" vs "overdue" overdue = open and past due; late = returned past due Loan.Overdue vs Loan.DaysLate
3 "member" vs "user" Member = library role; User = login membership package, auth is separateReal scenario: a team discovers that "customer" in sales means a company and in support means a person; two bounded contexts, two models (Bounded Context, Event Storming as a bigger-room version of this step).
Fix: keep the glossary in the repository (docs/glossary.md), review it in pull requests, and rename code when the language changes.
GRASP: assigning responsibilities Must-know
In plain words: nine rules of thumb that answer, "which class should do this?".
Common misunderstanding: "GRASP is a set of design patterns to implement." It is a teaching aid. Larman's own claim, as Wikipedia quotes it, is that "the critical design tool for software development is a mind well educated in design principles. It is not UML or any other technology."
Definition: GRASP stands for General Responsibility Assignment Software Patterns. The nine principles, with Wikipedia's problem statements:
| Principle | Problem it answers | Solution in short | Misuse |
|---|---|---|---|
| Information Expert | "What is a basic principle by which to assign responsibilities to objects?" | "Assign responsibility to the class that has the information needed to fulfill it." | Putting persistence there because the class "has the data" (violates cohesion) |
| Creator | Who creates object A? | B creates A if B contains, aggregates, records, closely uses or has the initialising data for A | Hard-wiring concrete construction where a factory is needed |
| Controller | Who handles a system event? | A non-UI class that represents the system or a use case receives and coordinates the operation | A "god controller"; business logic in the controller |
| Low Coupling | How to reduce the impact of change? | Prefer the assignment that adds the fewest dependencies | Removing all coupling (nothing talks) |
| High Cohesion | How to keep classes focused? | Keep responsibilities strongly related | Splitting until every class is one method |
| Polymorphism | How to handle alternatives by type? | Give each type the variant behaviour and call it polymorphically | An interface with one implementation forever |
| Pure Fabrication | What if expert breaks coupling or cohesion? | Invent a class that is not a domain concept (DDD calls it a service) | A dumping ground named Manager |
| Indirection | How to avoid direct coupling between A and B? | An intermediary object mediates | Layers of pass-through classes |
| Protected Variations | How to protect against likely change? | Wrap the point of instability in an interface and implement variants behind it | Predicting changes that never come |
Responsibility: "how many days late is this loan?" (CRC card Loan, GRASP applied)
1 Candidate A: ReportController computes from fields needs Loan's due and returned dates -> couples it to Loan internals
2 Candidate B: Loan computes from its own fields Information Expert: Loan has the data
3 Candidate C: a LoanUtils class with a static function Pure Fabrication without a reason: low cohesion
4 Choice: B. Fee amount: FeePolicy chosen by member category Polymorphism: no switch on category in callersReal scenario: the grasp snippets below: a controller with a switch on member category and date arithmetic becomes Loan.DaysLate plus a FeePolicy interface.
Fix: during a CRC session, when a responsibility has two plausible owners, apply the principles in order: expert first; then coupling and cohesion as judges; then polymorphism and protected variations for the parts that vary.
Failure modes Important
In plain words: the usual ways a design process goes wrong.
Common misunderstanding: "More process prevents these." They are mostly caused by missing feedback, not by missing documents.
Definition: the recurring failures and their signs.
| Failure | Sign | Why it happens | Cure |
|---|---|---|---|
| Designing the database first | ERD before any scenario; controllers full of logic; "Loan" is a table with a status column | The schema is the most concrete thing | Cards and scenarios first, schema derived and reviewed against access patterns |
| Skipping conceptual design | First class names come from the framework (LoanController, LoanModel) | Time pressure, "we know the domain" | A one-hour card session with a domain expert |
| Gold plating | Plugin system for fee rules before a second rule exists | Fear of change, cleverness | Scenario-driven cards; YAGNI (Fowler: a presumed future capability "should not be built now") |
| Analysis paralysis | Third redraw of the diagram, no code | Fear of being wrong | Time box, then a spike |
| Big design up front | A 60-page design, frozen | Confusing planning with design | Design the next story, review, repeat |
| Design by committee | Every option kept | Avoiding conflict | A named decision owner, an ADR |
| Resume-driven design | Kubernetes and Kafka for 200 loans a day | Novelty | Satisficing with written thresholds |
| No record | Same debate repeated | No ADRs | Supersede, do not forget |
Database-first path Conceptual-first path
1 ERD: loans(id, member_id, copy_id, status) Cards: Loan knows due date, says if overdue
2 Controller: if status = 'out' and due < now ... Scenario: renew refused when another member waits
3 Rule "renew once" copied into 3 controllers Rule lives in Loan.Renew
4 New rule "children get 7 days": edit 3 controllers New rule: change one FeePolicy / one Loan methodReal scenario: a ticketing system whose orders.status column grew from 3 to 14 values and whose rules are scattered across controllers, because the table came first.
Fix: use the cards to decide behaviour, derive the schema from the access paths the scenarios need, and keep the glossary honest.
Per-language and per-framework view
Where do cards, responsibilities and collaborators land in each ecosystem?
| Design idea | Go | Laravel (PHP 8.4) | Java / Spring | .NET | Python (Django) |
|---|---|---|---|---|---|
| CRC card (a concept) | A type, in a package named after the concept | A class in a module folder | A class in a package | A class in a project/namespace | A class in an app |
| Responsibility | A method or function | A method on a model, value object or action | A method | A method | A method |
| Collaborator | A field of interface type or a function parameter | A constructor parameter, resolved by the service container | A constructor-injected bean | A constructor-injected service | An imported module or injected callable |
| Controller (GRASP) | lending.Service called by an HTTP handler | An invokable Action class called by a controller | @Service use-case class | Application service, MediatR handler | A service function called by a view |
| Pure Fabrication | Clock, Ledger, repository types | Loans repository interface, Clock from Carbon::setTestNow or an injected ClockInterface | @Repository | IRepository | Repository module |
| Indirection / port | Small consumer-defined interface | Interface bound in a service provider | Interface plus @Configuration | Interface plus DI registration | Protocol or abstract base class |
| Module boundary | Package, internal/ enforced by the go command | Folder or Composer package with its own service provider | Java module or Maven module | Project reference | Django app |
| Registration | main wires everything (composition root) | bootstrap/providers.php lists providers | Component scan | Program.cs | INSTALLED_APPS |
Go's own guidance fits the process: Effective Go says the package name "should be good" because it is the accessor for its contents, so a package named after a glossary concept (catalog, lending) is a design statement. Laravel gives each concern a documented slot (Form Request, Policy, Job, Listener) but, as the SRP page notes, an "Action" is a convention, not a framework class.
Mechanics
From cards to code Must-know
The translation is mechanical on purpose, so the card session is not wasted.
| On the card | In Go | In Laravel | Rule |
|---|---|---|---|
| Class name | type Loan struct in package lending | final readonly class Loan in Modules\Lending | The glossary term, unchanged |
| "know X" | A field, unexported unless callers need it | A constructor-promoted property | Keep state private to the card |
| "do Y" | A method on the type | A public method | One verb phrase, one behaviour |
| Collaborator that is asked for information | A parameter or field of interface type | Constructor-injected interface | The interface is named by what the card needs |
| Collaborator that is asked to act | Same | Same, often behind an adapter | Ask at the boundary, not through the other card's internals |
| Card with no behaviour | A plain struct or DTO, maybe delete the card | A value object or array shape | Question the card |
| Card the group cannot name | Not a class yet | Not a class yet | Keep it a note |
| Responsibility with two owners | Apply GRASP | Apply GRASP | Record the decision |
Card Go Laravel
1 Loan lending.Loan Modules\Lending\Loan
2 Lending (controller) lending.Service Modules\Lending\CheckOutBook
3 FeePolicy lending.FeePolicy (interface) Modules\Lending\FeePolicy
4 Copy / Title catalog.Catalog (owns both) Modules\Catalog\CatalogApi
5 Member membership.Member Modules\Membership\MembershipApiResponsibility-assignment checklist Important
When a responsibility has no obvious owner, walk this list and write down the answers.
| Order | Question | If yes |
|---|---|---|
| 1 | Does exactly one card already hold the data? | Information Expert: give it there |
| 2 | Is this about creating an object? | Creator: whoever records, contains or closely uses it |
| 3 | Is it the entry point of a system operation? | Controller: one use-case class per operation |
| 4 | Does it vary by type, category or provider? | Polymorphism behind an interface |
| 5 | Would the obvious owner gain a second reason to change? | High Cohesion fails: invent a Pure Fabrication |
| 6 | Would the obvious owner depend on something volatile? | Indirection / Protected Variations: a port |
| 7 | Of the remaining options, which adds fewer dependencies? | Low Coupling: choose it |
Time boxes and stop rules Good to know
| Activity | Typical box | Stop when |
|---|---|---|
| Elicitation round | 1 to 2 hours per story group | Stories have acceptance criteria |
| CRC session | 60 to 90 minutes | Two or three scenarios pass with no new cards |
| Spike | 30 minutes to 2 days (XP: a pair for a week or two at most) | The question is answered, or the box ends (answer "unknown, here is the risk") |
| Design doc first draft | 1 to 3 days | Alternatives and non-goals are written |
| Review round | 2 to 5 days elapsed | Blocking comments resolved |
| ADR | 30 minutes | One decision, one page |
Worked example: library lending, from stories to code
We design a small lending system twice at the same time: as the process the page describes, and as the code it leads to. All snippets are under docs/snippets/design/design-process/; the Go module is academy/design-process, the PHP files are Laravel 13 sketches (reviewed, not run).
Step 1: stories and acceptance criteria
| ID | User story | Acceptance criteria |
|---|---|---|
| US-1 | As a member I can search the catalogue so I can find a book | Search matches title or author, case-insensitive |
| US-2 | As a member I can borrow an available copy | Copy leaves the shelf; due in 14 days; refused above my limit (adult 5, child 3, staff 10) |
| US-3 | As a member I can renew a loan once | A second renewal is refused; refused if another member waits |
| US-4 | As a member I return a copy | Copy returns to the shelf; late fee shown |
| US-5 | As a librarian I see overdue loans | Only open loans past their due date, oldest first |
| US-6 | As a member I can reserve a title with no available copy | Reservation is kept; renewals of those loans are blocked |
Non-goals (written down on purpose): payments for fees, lost-item handling, multi-branch transfers, e-books.
Step 2: glossary
The glossary table in Domain model first pass is the output: Title, Copy, Member, Loan, Reservation, Fee, Overdue. "Book" is banned in code because it hides the Title and Copy split.
Step 3: CRC cards
The table is the state after the session: the Ledger card did not exist at the start, it was added when the walk-through in Step 4 asked "who counts open loans?".
| Card | Responsibilities | Collaborators |
|---|---|---|
| Member | know own category; know own loan limit | none |
| Title | know ISBN, name, author; match a search query | Copy |
| Copy | know own barcode; know if on the shelf; be taken; be put back | none |
| Loan | know due date; say if overdue; renew itself; compute days late | Copy, Member |
| Ledger | record loans; count open loans of a member; create a Loan | Loan |
| Lending | check out a copy; renew a loan; accept a return; list overdue loans | Member, Copy, Loan, Ledger, FeePolicy, Reservation |
| FeePolicy | turn days late into a fee | none |
| Reservation | know who waits for which title; tell Lending a copy is wanted | Member, Title |
Step 4: scenario walk-through
Scenario US-2: M-7 (adult) checks out copy C-1
1 Lending -> Member: what is M-7's limit? Member: 5
2 Lending -> Ledger: how many open loans for M-7? Ledger: 2 (new card found here)
3 Lending : 2 < 5, allowed
4 Lending -> Copy: take C-1 Copy: ok / "not on the shelf"
5 Lending -> Ledger: open a Loan Ledger creates Loan L0001, due +14d
Scenario US-3: M-7 renews L0001
6 Lending -> Reservation: is anyone waiting for this copy? Reservation: no
7 Lending -> Loan: renew Loan: due +14d, renewals 1
8 Lending -> Loan: renew again Loan: refused (renewal limit)
Scenario US-4: M-7 returns L0001 39 days after checkout (due on day 28 after the renewal)
9 Lending -> Loan: days late? Loan: 11
10 Lending -> FeePolicy(adult): fee for 11 days FeePolicy: 275 (cap 1000)
11 Lending -> Copy: put back Copy: okStep 5: GRASP assignment
| Responsibility | Candidates | Choice | Principle |
|---|---|---|---|
| Days late | Controller, Loan, utility | Loan | Information Expert (it owns due and returned dates) |
| Count open loans for a member | Loan, Member, Lending | Ledger | Information Expert: it holds all loans; Pure Fabrication (not a domain noun) |
| Create a Loan | Lending, Member, Ledger | Ledger | Creator: it records loans |
| Fee by category | switch in Lending, policy objects | FeePolicy implementations | Polymorphism, Protected Variations |
| Receive "check out" | Handler, Lending | lending.Service / CheckOutBook | Controller |
| Talk to catalog and membership | Direct imports, own ports | Shelf, Members, Holds interfaces | Low Coupling, Indirection |
| Current time | time.Now() everywhere | Clock | Pure Fabrication (testability) |
Step 6: from cards to Go packages and Laravel modules
Go (academy/design-process/library) Laravel (app/Modules)
1 catalog/ Title, Copy, Take, Put Catalog/CatalogApi.php (public face)
2 membership/ Member, LoanLimit Membership/MembershipApi.php (public face)
3 lending/ Loan, Ledger, FeePolicy, Service Lending/Domain.php, CheckOutBook.php
4 cmd/demo/ composition root + adapters Lending/Infrastructure.php + LendingServiceProvider
5 (tests) lending/lending_test.go Pest or PHPUnit tests on Domain onlyDependencies point inward: lending imports neither catalog nor membership; the composition root (Go main, Laravel service provider) adapts them. That is DIP falling out of GRASP Indirection.
Go
Before
A report controller decides the fee itself: it reads the loan's fields, switches on the member category and does the calendar arithmetic.
// Before: a report controller reaches into loans and decides everything itself.
// It "knows" the fee rules, the categories and the calendar arithmetic.
package main
import (
"fmt"
"time"
)
type Loan struct {
MemberCategory string
Due time.Time
Returned time.Time
}
type ReportController struct{}
func (ReportController) LateFee(l Loan) int {
days := int(l.Returned.Sub(l.Due).Hours() / 24)
if days < 0 {
days = 0
}
switch l.MemberCategory {
case "adult":
fee := days * 25
if fee > 1000 {
fee = 1000
}
return fee
case "child":
return days * 5
case "staff":
return 0
}
return 0
}
func main() {
due := time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC)
l := Loan{"adult", due, due.AddDate(0, 0, 10)}
fmt.Println(ReportController{}.LateFee(l))
}After
Loan.DaysLate answers what only the loan can answer (Information Expert), FeePolicy varies by category (Polymorphism, Protected Variations), and the controller only coordinates. Output is identical (250) before and after; the next fee rule touches one type.
// After: each decision sits with the class that has the information (Information
// Expert), the fee rule varies by polymorphism, and the controller only coordinates.
package main
import (
"fmt"
"time"
)
type Cents int
// FeePolicy is a Protected Variations point: category rules change, callers do not.
type FeePolicy interface {
Fee(daysLate int) Cents
}
type PerDay struct{ Rate, Cap Cents }
func (p PerDay) Fee(daysLate int) Cents {
fee := Cents(daysLate) * p.Rate
if p.Cap > 0 && fee > p.Cap {
return p.Cap
}
return fee
}
type NoFee struct{}
func (NoFee) Fee(int) Cents { return 0 }
// Loan is the Information Expert for "how late am I": it owns Due and Returned.
type Loan struct {
Due time.Time
Returned time.Time
}
func (l Loan) DaysLate() int {
if !l.Returned.After(l.Due) {
return 0
}
return int(l.Returned.Sub(l.Due).Hours() / 24)
}
// Controller coordinates one system operation and does little work itself.
type Controller struct{ policies map[string]FeePolicy }
func (c Controller) LateFee(category string, l Loan) Cents {
p, ok := c.policies[category]
if !ok {
p = NoFee{}
}
return p.Fee(l.DaysLate())
}
func main() {
c := Controller{policies: map[string]FeePolicy{
"adult": PerDay{Rate: 25, Cap: 1000},
"child": PerDay{Rate: 5},
"staff": NoFee{},
}}
due := time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC)
fmt.Println(c.LateFee("adult", Loan{due, due.AddDate(0, 0, 10)}))
}The library example in Go
The three domain packages and the composition root. Read lending.go first: it owns the ports, the Loan, the Ledger (Creator) and the Service (Controller).
// Package lending owns the borrowing process. It defines the small interfaces it
// needs (Shelf, Members, Holds, Clock) so catalog and membership never import it.
package lending
import (
"errors"
"fmt"
"sort"
"sync"
"time"
)
type Cents int
var (
ErrLimitReached = errors.New("lending: loan limit reached")
ErrRenewalLimit = errors.New("lending: renewal limit reached")
ErrHeld = errors.New("lending: another member is waiting for this title")
ErrNoSuchLoan = errors.New("lending: no such loan")
ErrClosed = errors.New("lending: loan already closed")
)
// Ports: what Lending needs from the outside, in Lending's own words (Indirection).
type Shelf interface {
Take(copyID string) error
Put(copyID string) error
}
type Profile struct {
Category string
LoanLimit int
}
type Members interface {
Profile(memberID string) (Profile, error)
}
type Holds interface {
Waiting(copyID string) bool
}
type Clock interface{ Now() time.Time }
// FeePolicy varies by member category (Polymorphism, Protected Variations).
type FeePolicy interface{ Fee(daysLate int) Cents }
type PerDay struct{ Rate, Cap Cents }
func (p PerDay) Fee(daysLate int) Cents {
fee := Cents(daysLate) * p.Rate
if p.Cap > 0 && fee > p.Cap {
return p.Cap
}
return fee
}
type NoFee struct{}
func (NoFee) Fee(int) Cents { return 0 }
const (
loanTerm = 14 * 24 * time.Hour
maxRenewals = 1
hoursPerDay = 24
renewalExtends = loanTerm
)
// Loan is the Information Expert for everything about one borrowing.
type Loan struct {
ID string
CopyID string
MemberID string
Category string
Due time.Time
Renewals int
ReturnedAt *time.Time
}
func (l Loan) Open() bool { return l.ReturnedAt == nil }
func (l Loan) Overdue(now time.Time) bool { return l.Open() && now.After(l.Due) }
func (l Loan) DaysLate(at time.Time) int {
if !at.After(l.Due) {
return 0
}
return int(at.Sub(l.Due).Hours() / hoursPerDay)
}
func (l *Loan) Renew() error {
if l.Renewals >= maxRenewals {
return ErrRenewalLimit
}
l.Due = l.Due.Add(renewalExtends)
l.Renewals++
return nil
}
// Ledger records loans, so by the Creator rule it is the one that creates them.
type Ledger struct {
mu sync.Mutex
next int
loans map[string]*Loan
}
func NewLedger() *Ledger { return &Ledger{loans: map[string]*Loan{}} }
func (g *Ledger) open(copyID, memberID, category string, now time.Time) Loan {
g.mu.Lock()
defer g.mu.Unlock()
g.next++
l := &Loan{ID: fmt.Sprintf("L%04d", g.next), CopyID: copyID, MemberID: memberID, Category: category, Due: now.Add(loanTerm)}
g.loans[l.ID] = l
return *l
}
func (g *Ledger) countOpen(memberID string) int {
g.mu.Lock()
defer g.mu.Unlock()
n := 0
for _, l := range g.loans {
if l.MemberID == memberID && l.Open() {
n++
}
}
return n
}
func (g *Ledger) with(id string, fn func(*Loan) error) (Loan, error) {
g.mu.Lock()
defer g.mu.Unlock()
l, ok := g.loans[id]
if !ok {
return Loan{}, ErrNoSuchLoan
}
err := fn(l)
return *l, err
}
// Service is the GRASP Controller: one method per system operation, little logic.
type Service struct {
shelf Shelf
members Members
holds Holds
ledger *Ledger
fees map[string]FeePolicy
clock Clock
}
func NewService(s Shelf, m Members, h Holds, g *Ledger, fees map[string]FeePolicy, c Clock) *Service {
return &Service{shelf: s, members: m, holds: h, ledger: g, fees: fees, clock: c}
}
func (s *Service) CheckOut(memberID, copyID string) (Loan, error) {
p, err := s.members.Profile(memberID)
if err != nil {
return Loan{}, err
}
if s.ledger.countOpen(memberID) >= p.LoanLimit {
return Loan{}, ErrLimitReached
}
if err := s.shelf.Take(copyID); err != nil {
return Loan{}, err
}
return s.ledger.open(copyID, memberID, p.Category, s.clock.Now()), nil
}
func (s *Service) Renew(loanID string) (Loan, error) {
return s.ledger.with(loanID, func(l *Loan) error {
if !l.Open() {
return ErrClosed
}
if s.holds.Waiting(l.CopyID) {
return ErrHeld
}
return l.Renew()
})
}
// Return closes the loan, puts the copy back and answers with the late fee.
func (s *Service) Return(loanID string) (Cents, error) {
var fee Cents
_, err := s.ledger.with(loanID, func(l *Loan) error {
if !l.Open() {
return ErrClosed
}
now := s.clock.Now()
policy, ok := s.fees[l.Category]
if !ok {
policy = NoFee{}
}
fee = policy.Fee(l.DaysLate(now))
l.ReturnedAt = &now
return s.shelf.Put(l.CopyID)
})
return fee, err
}
func (s *Service) Overdue() []Loan {
s.ledger.mu.Lock()
defer s.ledger.mu.Unlock()
now := s.clock.Now()
var out []Loan
for _, l := range s.ledger.loans {
if l.Overdue(now) {
out = append(out, *l)
}
}
sort.Slice(out, func(i, j int) bool { return out[i].Due.Before(out[j].Due) })
return out
}// Package catalog owns what the library holds: titles (the work) and copies
// (the physical items). It knows nothing about members or loans.
package catalog
import (
"errors"
"strings"
"sync"
)
type ISBN string
type CopyID string
var (
ErrUnknownCopy = errors.New("catalog: unknown copy")
ErrNotOnShelf = errors.New("catalog: copy is not on the shelf")
)
type Title struct {
ISBN ISBN
Name string
Author string
}
// Matches is the Information Expert for "does this title fit a query".
func (t Title) Matches(q string) bool {
q = strings.ToLower(q)
return strings.Contains(strings.ToLower(t.Name), q) || strings.Contains(strings.ToLower(t.Author), q)
}
type copyState struct {
isbn ISBN
onShelf bool
}
type Catalog struct {
mu sync.Mutex
titles map[ISBN]Title
copies map[CopyID]*copyState
}
func New() *Catalog {
return &Catalog{titles: map[ISBN]Title{}, copies: map[CopyID]*copyState{}}
}
func (c *Catalog) AddTitle(t Title) {
c.mu.Lock()
defer c.mu.Unlock()
c.titles[t.ISBN] = t
}
func (c *Catalog) AddCopy(id CopyID, isbn ISBN) {
c.mu.Lock()
defer c.mu.Unlock()
c.copies[id] = ©State{isbn: isbn, onShelf: true}
}
func (c *Catalog) Search(q string) []Title {
c.mu.Lock()
defer c.mu.Unlock()
var out []Title
for _, t := range c.titles {
if t.Matches(q) {
out = append(out, t)
}
}
return out
}
// Take removes a copy from the shelf. The check and the change happen under one lock.
func (c *Catalog) Take(id CopyID) error {
c.mu.Lock()
defer c.mu.Unlock()
cp, ok := c.copies[id]
if !ok {
return ErrUnknownCopy
}
if !cp.onShelf {
return ErrNotOnShelf
}
cp.onShelf = false
return nil
}
func (c *Catalog) Put(id CopyID) error {
c.mu.Lock()
defer c.mu.Unlock()
cp, ok := c.copies[id]
if !ok {
return ErrUnknownCopy
}
cp.onShelf = true
return nil
}// Package membership owns who may borrow and how much. It knows nothing about loans.
package membership
import "errors"
type Category string
const (
Adult Category = "adult"
Child Category = "child"
Staff Category = "staff"
)
var ErrUnknownMember = errors.New("membership: unknown member")
type Member struct {
ID string
Name string
Category Category
}
// LoanLimit is the Information Expert answer: the member's category decides it.
func (m Member) LoanLimit() int {
switch m.Category {
case Child:
return 3
case Staff:
return 10
default:
return 5
}
}
type Directory struct{ members map[string]Member }
func NewDirectory(ms ...Member) *Directory {
d := &Directory{members: map[string]Member{}}
for _, m := range ms {
d.members[m.ID] = m
}
return d
}
func (d *Directory) Find(id string) (Member, error) {
m, ok := d.members[id]
if !ok {
return Member{}, ErrUnknownMember
}
return m, nil
}The composition root is the only place that sees every concrete type. The adapters are one-line translations:
// Composition root: the only place that knows every concrete piece. The adapters
// translate catalog and membership types into the words Lending asked for.
package main
import (
"fmt"
"time"
"academy/design-process/library/catalog"
"academy/design-process/library/lending"
"academy/design-process/library/membership"
)
type shelfAdapter struct{ c *catalog.Catalog }
func (a shelfAdapter) Take(id string) error { return a.c.Take(catalog.CopyID(id)) }
func (a shelfAdapter) Put(id string) error { return a.c.Put(catalog.CopyID(id)) }
type membersAdapter struct{ d *membership.Directory }
func (a membersAdapter) Profile(id string) (lending.Profile, error) {
m, err := a.d.Find(id)
if err != nil {
return lending.Profile{}, err
}
return lending.Profile{Category: string(m.Category), LoanLimit: m.LoanLimit()}, nil
}
type noHolds struct{}
func (noHolds) Waiting(string) bool { return false }
type fakeClock struct{ t time.Time }
func (c *fakeClock) Now() time.Time { return c.t }
func main() {
cat := catalog.New()
cat.AddTitle(catalog.Title{ISBN: "978-0-13-468599-1", Name: "The Pragmatic Programmer", Author: "Hunt, Thomas"})
cat.AddCopy("C-1", "978-0-13-468599-1")
dir := membership.NewDirectory(membership.Member{ID: "M-7", Name: "Sara", Category: membership.Adult})
clock := &fakeClock{t: time.Date(2026, 11, 1, 9, 0, 0, 0, time.UTC)}
svc := lending.NewService(shelfAdapter{cat}, membersAdapter{dir}, noHolds{}, lending.NewLedger(),
map[string]lending.FeePolicy{"adult": lending.PerDay{Rate: 25, Cap: 1000}}, clock)
loan, err := svc.CheckOut("M-7", "C-1")
fmt.Println(loan.ID, loan.Due.Format("2006-01-02"), err)
_, err = svc.CheckOut("M-7", "C-1")
fmt.Println("second checkout:", err)
clock.t = clock.t.AddDate(0, 0, 20)
fmt.Println("overdue:", len(svc.Overdue()))
fee, err := svc.Return(loan.ID)
fmt.Println("fee cents:", fee, err)
}The scenario from Step 4 becomes tests that use fakes for every port, with no database or clock:
package lending_test
import (
"errors"
"testing"
"time"
"academy/design-process/library/lending"
)
type shelf struct{ out map[string]bool }
func (s *shelf) Take(id string) error {
if s.out[id] {
return errors.New("taken")
}
s.out[id] = true
return nil
}
func (s *shelf) Put(id string) error { delete(s.out, id); return nil }
type members struct{ limit int }
func (m members) Profile(string) (lending.Profile, error) {
return lending.Profile{Category: "adult", LoanLimit: m.limit}, nil
}
type holds struct{ waiting bool }
func (h holds) Waiting(string) bool { return h.waiting }
type clock struct{ t time.Time }
func (c *clock) Now() time.Time { return c.t }
func newService(limit int, waiting bool) (*lending.Service, *clock) {
c := &clock{t: time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC)}
fees := map[string]lending.FeePolicy{"adult": lending.PerDay{Rate: 25, Cap: 1000}}
return lending.NewService(&shelf{out: map[string]bool{}}, members{limit}, holds{waiting}, lending.NewLedger(), fees, c), c
}
func TestLimit(t *testing.T) {
s, _ := newService(1, false)
if _, err := s.CheckOut("m", "c1"); err != nil {
t.Fatal(err)
}
if _, err := s.CheckOut("m", "c2"); !errors.Is(err, lending.ErrLimitReached) {
t.Fatalf("want limit, got %v", err)
}
}
func TestRenewOnceOnly(t *testing.T) {
s, _ := newService(5, false)
l, _ := s.CheckOut("m", "c1")
if _, err := s.Renew(l.ID); err != nil {
t.Fatal(err)
}
if _, err := s.Renew(l.ID); !errors.Is(err, lending.ErrRenewalLimit) {
t.Fatalf("want renewal limit, got %v", err)
}
}
func TestRenewBlockedByHold(t *testing.T) {
s, _ := newService(5, true)
l, _ := s.CheckOut("m", "c1")
if _, err := s.Renew(l.ID); !errors.Is(err, lending.ErrHeld) {
t.Fatalf("want held, got %v", err)
}
}
func TestLateFeeCapped(t *testing.T) {
s, c := newService(5, false)
l, _ := s.CheckOut("m", "c1")
c.t = c.t.AddDate(0, 0, 14+100)
fee, err := s.Return(l.ID)
if err != nil || fee != 1000 {
t.Fatalf("fee %d err %v", fee, err)
}
}The Go angle
Go makes this process cheap in four ways. Interfaces are satisfied implicitly, so lending can define Shelf without catalog ever knowing about it: the consumer defines the port, which is Indirection with no inheritance. The go command refuses import cycles, so two modules that "need each other" are caught at build time and you must find the real owner of the concept. internal/ is enforced, so helpers do not become accidental public API. And a package is the unit you name from the glossary, so the card-to-package mapping is one-to-one. A common Go smell is the reverse: starting with one package per layer (models, services, controllers) instead of one per concept, which is the database-first shape in folders.
Laravel
Before
The same controller-decides shape in PHP: it reaches into $loan->member->category and branches.
<?php
// app/Http/Controllers/ReportController.php: the controller knows the fee rules,
// the member categories and the calendar arithmetic. Every rule change lands here.
namespace App\Http\Controllers;
use App\Models\Loan;
final class ReportController
{
public function lateFee(Loan $loan): int
{
$days = max(0, (int) $loan->due_at->diffInDays($loan->returned_at, false));
return match ($loan->member->category) {
'adult' => min($days * 25, 1000),
'child' => $days * 5,
default => 0,
};
}
}After
<?php
// Information Expert + Polymorphism + Controller: the rule moves to the class that
// has the data, the variation sits behind an interface, the controller only coordinates.
namespace App\Lending;
use Carbon\CarbonImmutable;
interface FeePolicy
{
public function fee(int $daysLate): int; // cents
}
final readonly class PerDay implements FeePolicy
{
public function __construct(private int $rate, private int $cap = 0) {}
public function fee(int $daysLate): int
{
$fee = $daysLate * $this->rate;
return $this->cap > 0 ? min($fee, $this->cap) : $fee;
}
}
final readonly class NoFee implements FeePolicy
{
public function fee(int $daysLate): int
{
return 0;
}
}
final readonly class Loan
{
public function __construct(
public CarbonImmutable $due,
public ?CarbonImmutable $returnedAt = null,
) {}
// The loan owns Due and ReturnedAt, so it answers "how late am I".
public function daysLate(): int
{
if ($this->returnedAt === null || ! $this->returnedAt->greaterThan($this->due)) {
return 0;
}
return (int) $this->due->diffInDays($this->returnedAt);
}
}
// app/Http/Controllers/ReportController.php
namespace App\Http\Controllers;
use App\Lending\FeePolicy;
use App\Lending\Loan;
final class ReportController
{
/** @param array<string, FeePolicy> $policies keyed by member category */
public function __construct(private array $policies) {}
public function lateFee(string $category, Loan $loan): int
{
return ($this->policies[$category] ?? new \App\Lending\NoFee())->fee($loan->daysLate());
}
}The library example in Laravel
A modular-monolith layout (the namespace Modules\ is mapped to app/Modules/ with a PSR-4 entry in composer.json; Laravel itself does not require it): each module has a public API class, its own table, and a service provider that wires ports to adapters. bootstrap/providers.php is where providers are registered in Laravel 13 (the Laravel docs: "All user-defined service providers are registered in the bootstrap/providers.php file").
<?php
// app/Modules/Lending/Domain.php (split into one class per file in a real app).
// Pure PHP: no Eloquent, no HTTP, no framework imports except Carbon.
namespace Modules\Lending;
use Carbon\CarbonImmutable;
final class LoanLimitReached extends \DomainException {}
final class CopyNotOnShelf extends \DomainException {}
final class RenewalLimitReached extends \DomainException {}
final class UnknownMember extends \DomainException {}
// Ports: what Lending needs, in Lending's words. Adapters live in Infrastructure.
interface Shelf
{
public function take(string $copyId): bool;
public function put(string $copyId): void;
}
interface Members
{
/** @return array{category: string, loan_limit: int}|null */
public function profile(string $memberId): ?array;
}
interface Loans
{
public function countOpen(string $memberId): int;
public function open(string $copyId, string $memberId, string $category, CarbonImmutable $due): Loan;
public function find(string $loanId): ?Loan;
public function save(Loan $loan): void;
}
interface FeePolicy
{
public function fee(int $daysLate): int;
}
final readonly class PerDay implements FeePolicy
{
public function __construct(private int $rate, private int $cap = 0) {}
public function fee(int $daysLate): int
{
$fee = $daysLate * $this->rate;
return $this->cap > 0 ? min($fee, $this->cap) : $fee;
}
}
final readonly class NoFee implements FeePolicy
{
public function fee(int $daysLate): int
{
return 0;
}
}
// Information Expert for one borrowing: it owns the dates and the renewal count.
final readonly class Loan
{
public const int TERM_DAYS = 14;
public const int MAX_RENEWALS = 1;
public function __construct(
public string $id,
public string $copyId,
public string $memberId,
public string $category,
public CarbonImmutable $due,
public int $renewals = 0,
public ?CarbonImmutable $returnedAt = null,
) {}
public function isOpen(): bool
{
return $this->returnedAt === null;
}
public function isOverdue(CarbonImmutable $now): bool
{
return $this->isOpen() && $now->greaterThan($this->due);
}
public function daysLate(CarbonImmutable $at): int
{
return $at->greaterThan($this->due) ? (int) $this->due->diffInDays($at) : 0;
}
public function renew(): self
{
if ($this->renewals >= self::MAX_RENEWALS) {
throw new RenewalLimitReached();
}
return new self($this->id, $this->copyId, $this->memberId, $this->category,
$this->due->addDays(self::TERM_DAYS), $this->renewals + 1, $this->returnedAt);
}
public function close(CarbonImmutable $at): self
{
return new self($this->id, $this->copyId, $this->memberId, $this->category,
$this->due, $this->renewals, $at);
}
}<?php
// app/Modules/Lending/CheckOutBook.php: a GRASP Controller in Laravel clothes.
// One class per system operation: coordinates, owns the transaction, decides little.
namespace Modules\Lending;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\DB;
final class CheckOutBook
{
public function __construct(
private Shelf $shelf,
private Members $members,
private Loans $loans,
) {}
public function __invoke(string $memberId, string $copyId): Loan
{
return DB::transaction(function () use ($memberId, $copyId): Loan {
$profile = $this->members->profile($memberId) ?? throw new UnknownMember();
if ($this->loans->countOpen($memberId) >= $profile['loan_limit']) {
throw new LoanLimitReached();
}
if (! $this->shelf->take($copyId)) {
throw new CopyNotOnShelf();
}
return $this->loans->open(
$copyId, $memberId, $profile['category'],
CarbonImmutable::now()->addDays(Loan::TERM_DAYS),
);
});
}
}
// app/Modules/Lending/ReturnBook.php: the second system operation.
final class ReturnBook
{
/** @param array<string, FeePolicy> $fees keyed by member category */
public function __construct(
private Shelf $shelf,
private Loans $loans,
private array $fees,
) {}
/** @return int late fee in cents */
public function __invoke(string $loanId): int
{
return DB::transaction(function () use ($loanId): int {
$loan = $this->loans->find($loanId) ?? throw new \DomainException('Unknown loan');
$now = CarbonImmutable::now();
$fee = ($this->fees[$loan->category] ?? new NoFee())->fee($loan->daysLate($now));
$this->loans->save($loan->close($now));
$this->shelf->put($loan->copyId);
return $fee;
});
}
}<?php
// app/Modules/Lending/Infrastructure.php: adapters (Indirection, Protected Variations).
// They translate Catalog's and Membership's public APIs into Lending's own ports.
namespace Modules\Lending;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\DB;
use Modules\Catalog\CatalogApi;
use Modules\Membership\MembershipApi;
final class CatalogShelf implements Shelf
{
public function __construct(private CatalogApi $catalog) {}
public function take(string $copyId): bool
{
return $this->catalog->takeCopy($copyId);
}
public function put(string $copyId): void
{
$this->catalog->putCopy($copyId);
}
}
final class MembershipMembers implements Members
{
public function __construct(private MembershipApi $membership) {}
public function profile(string $memberId): ?array
{
// forUpdate serialises concurrent checkouts of one member inside the transaction.
return $this->membership->profile($memberId, forUpdate: true);
}
}
// Lending owns the "loans" table; nobody else reads it.
final class DbLoans implements Loans
{
public function countOpen(string $memberId): int
{
return DB::table('loans')->where('member_id', $memberId)->whereNull('returned_at')->count();
}
public function open(string $copyId, string $memberId, string $category, CarbonImmutable $due): Loan
{
$id = (string) \Illuminate\Support\Str::ulid();
DB::table('loans')->insert([
'id' => $id, 'copy_id' => $copyId, 'member_id' => $memberId,
'category' => $category, 'due_at' => $due, 'renewals' => 0,
]);
return new Loan($id, $copyId, $memberId, $category, $due);
}
public function find(string $loanId): ?Loan
{
$r = DB::table('loans')->where('id', $loanId)->lockForUpdate()->first();
return $r === null ? null : new Loan(
$r->id, $r->copy_id, $r->member_id, $r->category,
CarbonImmutable::parse($r->due_at), (int) $r->renewals,
$r->returned_at === null ? null : CarbonImmutable::parse($r->returned_at),
);
}
public function save(Loan $loan): void
{
DB::table('loans')->where('id', $loan->id)->update([
'due_at' => $loan->due, 'renewals' => $loan->renewals, 'returned_at' => $loan->returnedAt,
]);
}
}<?php
// app/Modules/Lending/Http.php: the delivery layer. It translates HTTP into one call.
namespace Modules\Lending;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\ServiceProvider;
use Modules\Catalog\CatalogApi;
use Modules\Membership\MembershipApi;
final class CheckOutRequest extends FormRequest
{
public function rules(): array
{
return [
'member_id' => ['required', 'string'],
'copy_id' => ['required', 'string'],
];
}
}
final class LoanController
{
public function store(CheckOutRequest $request, CheckOutBook $checkOut): JsonResponse
{
try {
$loan = $checkOut($request->string('member_id')->toString(), $request->string('copy_id')->toString());
} catch (LoanLimitReached|CopyNotOnShelf $e) {
return response()->json(['error' => class_basename($e)], 422);
}
return response()->json(['id' => $loan->id, 'due' => $loan->due->toDateString()], 201);
}
}
// app/Modules/Lending/LendingServiceProvider.php: the module's wiring, registered in
// bootstrap/providers.php. Swapping an adapter or a fee rule is a change in this file only.
final class LendingServiceProvider extends ServiceProvider
{
public function register(): void
{
$this->app->bind(Shelf::class, fn ($app) => new CatalogShelf($app->make(CatalogApi::class)));
$this->app->bind(Members::class, fn ($app) => new MembershipMembers($app->make(MembershipApi::class)));
$this->app->bind(Loans::class, DbLoans::class);
$this->app->bind(ReturnBook::class, fn ($app) => new ReturnBook(
$app->make(Shelf::class),
$app->make(Loans::class),
['adult' => new PerDay(25, 1000), 'child' => new PerDay(5), 'staff' => new NoFee()],
));
}
public function boot(): void
{
Route::middleware('api')->prefix('api')->group(function () {
Route::post('/loans', [LoanController::class, 'store']);
});
}
}<?php
// app/Modules/Catalog/CatalogApi.php: the public face of the Catalog module.
namespace Modules\Catalog;
use Illuminate\Support\Facades\DB;
final class CatalogApi
{
/** Atomic compare-and-set: returns false when the copy was not on the shelf. */
public function takeCopy(string $copyId): bool
{
return DB::table('copies')
->where('id', $copyId)
->where('on_shelf', true)
->update(['on_shelf' => false]) === 1;
}
public function putCopy(string $copyId): void
{
DB::table('copies')->where('id', $copyId)->update(['on_shelf' => true]);
}
}<?php
// app/Modules/Membership/MembershipApi.php: the ONLY class other modules may call.
// Eloquent models, tables and rules behind it are private to the module.
namespace Modules\Membership;
use Illuminate\Support\Facades\DB;
final class MembershipApi
{
/** @return array{category: string, loan_limit: int}|null */
public function profile(string $memberId, bool $forUpdate = false): ?array
{
$query = DB::table('members')->where('id', $memberId);
$row = ($forUpdate ? $query->lockForUpdate() : $query)->first(['category']);
if ($row === null) {
return null;
}
return [
'category' => $row->category,
'loan_limit' => match ($row->category) {
'child' => 3,
'staff' => 10,
default => 5,
},
];
}
}<?php
// database/migrations/2026_11_25_000000_create_loans_table.php: Lending's own table.
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('loans', function (Blueprint $table) {
$table->ulid('id')->primary();
$table->string('copy_id')->index(); // reference by id, no foreign key into Catalog
$table->string('member_id')->index(); // reference by id, no foreign key into Membership
$table->string('category');
$table->timestamp('due_at')->index();
$table->unsignedTinyInteger('renewals')->default(0);
$table->timestamp('returned_at')->nullable();
});
}
public function down(): void
{
Schema::dropIfExists('loans');
}
};The Laravel angle
| Card / GRASP role | Laravel construct | Note |
|---|---|---|
| Controller (GRASP) | An invokable action class (CheckOutBook), called by a thin HTTP controller | The HTTP controller is delivery; the action is the GRASP controller |
| Pure Fabrication | Repository interface (Loans), clock | Bound in the service provider |
| Indirection | Adapter classes bound with $this->app->bind | The container is the composition root |
| Information Expert | Plain readonly domain class, or an Eloquent model when the data is persistent | Do not move HTTP or mail into the model |
| Module boundary | A folder or Composer package per module, PSR-4 namespace, one provider | Convention, not a framework feature; enforce with architecture tests or CODEOWNERS |
| Transaction boundary | DB::transaction in the action | One transaction per system operation |
| Guarding a race | Atomic UPDATE ... WHERE on_shelf = 1 and lockForUpdate() | Both are in the snippets |
Laravel's own structure page says the default layout is "a great starting point" and you are free to organise as you wish, so modules are a design choice made with the same process, not something the framework decides for you.
Solving the classic problems
| Problem | Solution | How | Advantage | Cost / limitation |
|---|---|---|---|---|
| The team starts from the schema | Card session first | Stories, glossary, cards, scenarios; derive tables from access paths | Behaviour has a home | An hour before coding |
| Two owners fight for a responsibility | GRASP checklist | Expert, then coupling and cohesion | Decision with a reason | Needs practice |
| Endless design debate | Spike plus time box | Write the question, measure, record | Evidence ends opinion | Costs a day |
| Nobody remembers why | ADR | One page per significant decision | Cheap memory | Needs discipline |
| Design too big to review | Split into RFC plus small docs | One decision per doc | Faster reviews | More documents |
| Gold plating | Scenario-driven cards, YAGNI | Add a card only when a scenario needs it | Less code | May need later refactoring |
| Cards become stale | Treat them as props | Photograph, then record decisions in doc or code | No false authority | The cards themselves are discarded |
| Conceptual design disagrees with the database | Revisit cards | Update scenarios first, then schema | One source of truth | Rework |
Database first: the schema derived from the scenarios
After the cards, the schema follows from what scenarios ask. Checkout needs "count open loans for a member", renew needs "find by id and lock", the overdue report needs "open loans by due date":
-- Derived from the scenarios, not drawn first.
CREATE TABLE loans (
id char(26) PRIMARY KEY, -- ULID, generated by the application
copy_id text NOT NULL, -- reference by id, no foreign key into Catalog
member_id text NOT NULL, -- reference by id, no foreign key into Membership
category text NOT NULL, -- copied at checkout: the fee rule must not change retroactively
due_at timestamptz NOT NULL,
renewals smallint NOT NULL DEFAULT 0,
returned_at timestamptz
);
-- Scenario US-2: count open loans for one member.
CREATE INDEX loans_open_by_member ON loans (member_id) WHERE returned_at IS NULL;
-- Scenario US-5: overdue loans, oldest first.
CREATE INDEX loans_open_by_due ON loans (due_at) WHERE returned_at IS NULL;
SELECT id, member_id, copy_id, due_at
FROM loans
WHERE returned_at IS NULL AND due_at < now()
ORDER BY due_at;Note the two decisions the cards made that a table-first design would have missed: the member's category is copied onto the loan, and the loan references the copy and member by id so the modules can be split later. The partial indexes are PostgreSQL syntax; MySQL has no partial index, so there you index (member_id, returned_at) instead. See Schema Design.
Skipping conceptual design
Sign: the first class created is LoanController. Cure: before opening the IDE, run a thirty-minute card session on the first story. The cost is half an hour; the benefit is that Loan exists as a concept with behaviour before anything has an HTTP route.
Gold plating
Sign: a FeePolicyRegistry with plugin loading when there are three fixed categories. Cure: keep FeePolicy as an interface (it already earns its keep, three implementations exist) and delete the registry until a fourth rule arrives from outside the code base. See Open–Closed for when extension points pay off.
Choosing
How much design for which situation?
| Situation | Process to use | Artefacts | Reason |
|---|---|---|---|
| Bug fix, copy change, obvious refactor | None | Pull request description | Solution is not ambiguous (Google: do not write a design doc) |
| New feature in a known area, one team | 30-minute card session | Photo of cards, a few lines in the ticket | Cheap and shared |
| Feature with a risky unknown | Card session plus a spike | Spike answer in the ticket | Evidence beats opinion |
| New module or service | Cards, scenarios, design doc | Design doc, ADR for each big choice | Hard to reverse |
| Cross-team change, public API, schema others read | RFC | RFC with alternatives and unresolved questions | Needs consent |
| Regulated or safety-critical | Fuller documents per Parnas and Clements | Requirements, interfaces, reviews | Audit trail |
| Throwaway tool, one-off script | Sketch | None | Cost of design exceeds cost of change |
| If you are choosing between | Prefer | When |
|---|---|---|
| CRC cards and UML | Cards for discovery, UML to document stable structure | Always both, in that order (UML in Practice) |
| Throwaway and evolutionary prototype | Throwaway when the question is a single risk | Evolutionary when users are friendly and requirements will keep moving |
| Design doc and RFC | Design doc inside a team, RFC across teams | RFC when others must consent |
| ADR and design doc | ADR for one decision, doc for a project | Link them |
In architecture: from a single process to a distributed system
The process is the same at every scale: concepts, responsibilities, collaborations, scenarios, then decisions with reasons. What changes is what a "card" is and how expensive it is to be wrong.
Monolith: one process, one database
Cards become classes and packages; collaboration is a function call; a wrong card is a refactoring. The library example runs as one Go binary or one Laravel app with one database: DB::transaction wraps checkout, one UPDATE takes the copy. Start with conceptual design in a single session and a package per concept; Fowler's Monolith First explains why: "Almost all the successful microservice stories have started with a monolith that got too big and was broken up". Risk: a package that grows beyond one actor (SRP).
Modular monolith and multiple databases
The same cards are grouped into modules with public APIs, own tables, and no foreign keys across module borders (as in the migration above). Cross-module calls go through the CatalogApi and MembershipApi classes (or Go ports adapted in main). A card that two modules want is a sign the boundary is wrong. Enforce boundaries by tooling: Go internal/, CODEOWNERS, architecture tests. See Modular Monolith.
Microservices: service boundaries are CRC at a higher level
Service boundaries answer the same question as a card, one level up: "what does this group know and do, and whom must it ask?" Cards that talk a lot sit together (Loan, FeePolicy, Reservation inside Lending); cards that are only asked simple questions sit apart (Member). The collaborations that crossed a card boundary in-process now cross a network, so each needs a decision that a card never needed:
| In-process collaboration | Over the network | Decision to write down |
|---|---|---|
Lending asks Copy to be taken | HTTP/gRPC call POST /copies/C-1/take | Idempotency key; timeout; what if the call succeeds but the answer is lost |
Lending asks Member for limit | Synchronous call or a local copy of the data | Staleness versus availability |
DB::transaction around both | A saga or an outbox | Eventual consistency, compensation |
| "Copy available again" | An event LoanClosed | Schema versioning, ordering, duplicates |
Checkout as a saga across services (what the single transaction used to guarantee)
1 Lending -> Catalog: reserve copy C-1 (idempotency key = checkout-id) Catalog marks C-1 held
2 Lending : insert Loan L0001 with status pending
3 Lending -> Catalog: confirm C-1 Catalog marks C-1 out
4 failure at step 3 Lending -> Catalog: release C-1; Loan -> failed compensationConway's law frames the human side: "Any organization that designs a system (defined broadly) will produce a design whose structure is a copy of the organization's communication structure." So run the card session with the people who will own each side. See Service Boundaries and Monolith vs Microservices vs Modular Monolith. Cards from Event Storming sessions play the same role in a bigger room.
Distributed data: replicas, caches, multi-region
The cards show where consistency matters. Copy.be taken must be strongly consistent, so it runs against the primary (or a compare-and-set in a single-leader store). Title.match a search query can tolerate staleness, so it may be served from a read replica, a cache or a search engine with a known lag. The design document should state per card: strong or eventual, read-your-writes needed or not, and what the user sees during lag. This is where the compromise table becomes concrete: a cached "available now" shown in search can be a minute old, and the checkout still refuses when the atomic take fails.
Scaling path: 1×, 10×, 100×
| Load | Design state | Process activity |
|---|---|---|
| 1× (one branch) | Monolith, one database, scan for overdue | One card session; ADR "one database" |
| 10× (a city) | Indexes on due_at and member_id, read replica for search, cache for titles | Spike on query times; update ADR |
| 100× (a national network) | Split Catalog (read heavy) from Lending (write heavy), search service, events between them | RFC across teams; cards re-run at service level |
| Organisation grows | Boundaries follow teams | Revisit boundaries when ownership changes |
In production systems
Checkable examples of design processes in public:
- Google's design docs. The Design Docs at Google essay lists a structure (context and scope, goals and non-goals, the actual design, alternatives considered, cross-cutting concerns) and says the document should be written "in whatever form makes the most sense for the particular project". It also states when not to write one: when the solution is not ambiguous.
- Rust RFCs. The
rust-lang/rfcstemplate has the sections Summary, Motivation, Guide-level explanation, Reference-level explanation, Drawbacks, Rationale and alternatives, Prior art and Unresolved questions. The template says Motivation "is one of the most important sections of any RFC". - Architecture decision records. Nygard's 2011 post proposed the short format; the same idea is catalogued at adr.github.io. The format is Title, Context, Decision, Status, Consequences.
- XP spikes. The Extreme Programming rules page describes a spike as "a very simple program to explore potential solutions".
- CRC in an agile process. Ambler's Agile Modeling page describes CRC models for a single user story and notes that "a CRC model isn't carved in stone".
- Laravel and Go layouts. The Laravel 13 docs describe
bootstrap/providers.phpand service providers; the Go module layout andinternal/rule are documented on go.dev. Both give the composition-root and module-boundary mechanisms used above.
We could not read the Oxide RFD site (it requires sign-in), so we do not cite it.
Lab
All commands run from docs/snippets/design/design-process/go.
- Run the CRC checker.
go run ./crcprintsCRC: all cards consistent. Now delete theFeePolicycard line frommain.goand run it again. Expected:CRC: Lending collaborates with "FeePolicy", which has no card. Add three more responsibilities toLending(it has four, the threshold is six) and watch the overload warning. - Run the spike.
go run ./spike. Expected: scan time grows roughly linearly, about a millisecond for a million loans on a laptop. Write the answer in one sentence and delete the file (the exercise is the deleting). - GRASP before and after.
go run ./grasp/beforeandgo run ./grasp/afterboth print250. Now add a new rule (children pay 5 per day, capped at 200) in each. Inbeforeyou edit aswitch; inafteryou add onePerDayvalue. Count the lines you touched. - Run the scenarios as tests.
go test ./library/lending. Expected:ok. Add a test "child limit is 3": notice that you need only theMembersfake. - Run the composition root.
go run ./library/cmd/demo. Expected:L0001 2026-11-15 <nil>,second checkout: catalog: copy is not on the shelf,overdue: 1,fee cents: 150 <nil>. - Do your own session. Take a food-ordering app: stories "place an order", "pay", "cancel within 5 minutes", "restaurant accepts or rejects". Write the glossary (is
Cartthe same asOrder?), five cards, walk two scenarios, assign each responsibility with the checklist, and write one ADR (one database or two?). Then compare your cards with the library example's structure.
Common misconceptions
| Belief | Reality |
|---|---|
| Design is done before coding | Design is a loop; code and spikes feed back into it |
| CRC cards are obsolete UML | They are a discovery tool; UML documents what is stable |
| Conceptual design means drawing boxes | It means agreeing concepts, responsibilities and collaborations |
| A responsibility is a method | It is an obligation in problem words; it may be several methods or a field |
| More classes means better design | More classes can mean fragmentation; cohesion is the test |
| A spike is a first version | A spike is deleted; keep-worthy code is rewritten with tests |
| A prototype can be cleaned up later | Often it cannot; decide throwaway or evolutionary on day one |
| Design docs must be long | The Google essay: write them when the solution is ambiguous and keep them focused on trade-offs |
| Database first is faster | It is faster to the first table and slower to every later rule |
| GRASP is nine patterns to implement | It is a mental toolset (Larman) for assigning responsibilities |
| The best design maximises every quality | Qualities conflict; satisfice against thresholds you wrote down |
| Microservices need a different process | The same process, with network costs as extra decisions |
Cheat sheet
| Topic | Remember |
|---|---|
| Process | Elicit, conceptual, technical, spike, review, repeat |
| Parnas and Clements | Fake the rational process: document as if you had followed it, record rejected alternatives |
| Conceptual design | Mockups, model, responsibilities, collaborations; no databases or frameworks |
| Technical design | Classes, interfaces, data, algorithms, packages; constrained by tools |
| CRC card | Singular noun; verb-phrase responsibilities; collaborators; 4 by 6 inches |
| CRC session | One story, play the scenario aloud, add cards only on demand |
| GRASP | Expert, Creator, Controller, Low Coupling, High Cohesion, Polymorphism, Pure Fabrication, Indirection, Protected Variations |
| Compromise | Rank qualities, state thresholds, satisfice, record rejected options |
| Spike | Question, time box, answer in the doc, delete the code |
| Prototype | Throwaway or evolutionary, chosen up front |
| Review | Criteria checklist, blocking versus non-blocking, a decision owner |
| Documents | Design doc (project), RFC (needs consent), ADR (one decision) |
| Glossary | One sentence per term; code uses the same words |
| Database | Derived from scenarios and access patterns, not first |
| Monolith to microservices | Service boundaries are CRC one level up; network turns collaborations into decisions |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — What do the three parts of a CRC card stand for, and which part is asymmetric? Important
Answer
Answer: Class, Responsibility, Collaborator. Collaboration is not symmetric: Loan asks Copy, but Copy does not ask Loan.
2 — Why do Parnas and Clements say we should "fake" a rational design process? Good to know
Answer
Answer: No project follows the ideal order (requirements are incomplete, facts appear during implementation, errors happen), but following the ideal as closely as possible and writing the documentation as if we had gives guidance, fewer backtracks and a record readers can use. They also record rejected alternatives.
3 — What is the difference between conceptual and technical design? Must-know
Answer
Answer: Conceptual design decides what the parts are, what they know and do and who asks whom, in problem language (mockups, model, responsibilities, collaborations). Technical design decides how: classes, interfaces, data, algorithms, packages under the real tools and quality constraints.
4 — A controller computes late fees from a loan's fields. Which GRASP principles say what to change? Important
Answer
Answer: Information Expert moves the "days late" computation into Loan; Polymorphism and Protected Variations put the fee rule behind a FeePolicy interface; the controller keeps only coordination (Controller).
5 — What is satisficing and how does it apply to design? Important
Answer
Answer: Choosing the first option that meets an acceptability threshold instead of maximising. In design: state thresholds for the ranked quality attributes, pick an option that meets them, record rejected alternatives.
6 — When is a spike the right tool, and what happens to its code? Must-know
Answer
Answer: When a doubt about feasibility or estimates cannot be settled by discussion. It is time-boxed to one question; the answer is written down and the code is deleted ("most spikes are not good enough to keep").
7 — Throwaway versus evolutionary prototype: how do you choose? Important
Answer
Answer: Throwaway when you want to learn about a single risk or confirm requirements cheaply; evolutionary when you will keep refining the real system with user feedback. Decide before building, because structure is ignored in the first kind.
8 — What goes into an ADR and when do you write one? Must-know
Answer
Answer: Title, context, decision, status, consequences (Nygard). Write one per architecturally significant decision: structure, non-functional characteristics, dependencies, interfaces, construction techniques.
9 — Why is designing the database first risky? Must-know
Answer
Answer: It encodes entities as data holders, scatters behaviour into controllers and fixes decisions (foreign keys, status columns) before the scenarios have shown what the system must do. Derive the schema from scenarios and access patterns.
10 — How do CRC cards relate to microservice boundaries? Important
Answer
Answer: A service boundary is a card boundary one level up: it groups concepts that collaborate heavily and separates those with light collaboration. Collaborations that cross it become network calls and events, each needing decisions on timeouts, idempotency, consistency and versioning.
11 — Name GRASP's nine principles. Good to know
Answer
Answer: Information Expert, Creator, Controller, Low Coupling, High Cohesion, Polymorphism, Pure Fabrication, Indirection, Protected Variations.
Glossary
| Term | Meaning |
|---|---|
| Acceptance criteria | Testable conditions under which a user story counts as done |
| ADR (Architecture Decision Record) | A short record of one significant decision: title, context, decision, status, consequences |
| Alternatives considered | The design doc section listing rejected options and why |
| Collaborator | A card (class) another card must ask for help |
| Conceptual design | Deciding what the parts are, who knows what and who asks whom, in domain language |
| Conceptual model | The glossary plus a sketch of concepts and relationships |
| Controller (GRASP) | A non-UI class that receives and coordinates one system operation |
| Creator (GRASP) | The class that records, contains or closely uses B creates B |
| CRC card | Index card with Class, Responsibilities, Collaborators |
| Design doc | A short document on a project's design with goals, non-goals and alternatives |
| Design review | Examination of a design by people who did not write it |
| Evolutionary prototype | A prototype that is grown into the real system |
| Gold plating | Adding features or flexibility nobody asked for |
| GRASP | General Responsibility Assignment Software Patterns, Larman's nine principles |
| High Cohesion (GRASP) | Keep a class's responsibilities strongly related |
| Indirection (GRASP) | An intermediary that decouples two elements |
| Information Expert (GRASP) | Assign a responsibility to the class that has the needed information |
| Low Coupling (GRASP) | Prefer the assignment that adds the fewest dependencies |
| Mockup | A rough picture of a screen or output used to confirm a need |
| Non-goal | Something that could reasonably be a goal but is explicitly excluded |
| Polymorphism (GRASP) | Assign variant behaviour to the types that vary and call it polymorphically |
| Protected Variations (GRASP) | Wrap a point of instability in a stable interface |
| Pure Fabrication (GRASP) | A class that is not a domain concept, invented for cohesion or coupling |
| RFC (Request for Comments) | A proposal document circulated for review and consent |
| Responsibility | What a class knows or does, phrased as a short verb phrase |
| Role play | Acting out a scenario with each person holding a card |
| Satisficing | Choosing the first option that meets an acceptability threshold (Simon) |
| Scenario | A concrete walk through a story used to test cards |
| Spike | A time-boxed throwaway experiment answering one technical question |
| Technical design | Deciding how parts are built: classes, interfaces, data, algorithms |
| Throwaway prototype | A prototype built to be discarded |
| Tracer bullet / walking skeleton | A thin end-to-end slice that is kept and grown |
| Ubiquitous language | The shared, rigorous language of developers and domain experts |
| User story | A short statement of a need from a user's view |
| YAGNI | "You aren't gonna need it": do not build presumed future capability now |
References
Fetched and read; every URL below returned HTTP 200 when fetched.
- Kent Beck, Ward Cunningham, A Laboratory For Teaching Object-Oriented Thinking, OOPSLA '89: http://c2.com/doc/oopsla89/paper.html
- David L. Parnas, Paul C. Clements, A Rational Design Process: How and Why to Fake It: https://www.cs.tufts.edu/~nr/cs257/archive/david-parnas/fake-it.pdf; bibliographic record: https://api.crossref.org/works/10.1109/tse.1986.6312940
- Scott W. Ambler, Class Responsibility Collaborator (CRC) Models, Agile Modeling: http://agilemodeling.com/artifacts/crcModel.htm
- Wikipedia, GRASP (object-oriented design) (secondary source; quotes Larman): https://en.wikipedia.org/wiki/GRASP_(object-oriented_design)
- Wikipedia, Class-responsibility-collaboration card: https://en.wikipedia.org/wiki/Class-responsibility-collaboration_card
- Wikipedia, Satisficing (secondary): https://en.wikipedia.org/wiki/Satisficing
- Wikipedia, Software prototyping (secondary): https://en.wikipedia.org/wiki/Software_prototyping
- Don Wells, Create a Spike Solution, ExtremeProgramming.org: http://www.extremeprogramming.org/rules/spike.html
- Michael Nygard, Documenting Architecture Decisions, 15 November 2011: https://www.cognitect.com/blog/2011/11/15/documenting-architecture-decisions
- ADR catalogue: https://adr.github.io/
- Design Docs at Google, Industrial Empathy: https://www.industrialempathy.com/posts/design-docs-at-google/
- Rust RFC template: https://github.com/rust-lang/rfcs/blob/master/0000-template.md
- Martin Fowler, Monolith First: https://martinfowler.com/bliki/MonolithFirst.html
- Martin Fowler, Ubiquitous Language: https://martinfowler.com/bliki/UbiquitousLanguage.html
- Martin Fowler, Bounded Context: https://martinfowler.com/bliki/BoundedContext.html
- Martin Fowler, Yagni: https://martinfowler.com/bliki/Yagni.html
- Martin Fowler, Conway's Law: https://martinfowler.com/bliki/ConwaysLaw.html
- Effective Go: https://go.dev/doc/effective_go
- Laravel 13 docs, Structure and Service Providers: https://laravel.com/docs/13.x/structure, https://laravel.com/docs/13.x/providers
- Larman, Applying UML and Patterns (3rd ed., 2004): cited through Wikipedia, book not read.
- Wirfs-Brock and Wilkerson, Object-Oriented Design: a Responsibility-Driven Approach, OOPSLA '89: cited through Beck and Cunningham, not read.
- Simon, Rational Choice and the Structure of the Environment, Psychological Review, 1956: cited through Wikipedia, not read.