Low-Level Design: Classes, Responsibilities, Relationships, Structured vs OO Design
"Coupling is the measure of the strength of association established by a connection from one module to another." — W. P. Stevens, G. J. Myers, L. L. Constantine, Structured Design, IBM Systems Journal 13(2), 1974
Summary: Low-level design (LLD) decides which classes or functions exist, what each one is responsible for, how they relate, and what their public contracts look like, so that one component can be coded, tested and changed without guessing. It starts after high-level design (HLD) has chosen the components and ends where the code begins. Focus: structured design (structure charts, data-flow diagrams, top-down decomposition) against object-oriented design, when plain functions win, responsibility-driven design and role stereotypes, GRASP, the six class relationships, interface and method design, invariants, testability, data-structure choice, the LLD interview method, two full worked problems (a parking lot and a notification system) and LLD inside a microservice, in Go and Laravel. Learning goal: Given a vague requirement, produce a small, testable set of classes (or functions) with named responsibilities, clear relationships and honest contracts, draw them, walk one scenario through them, and say why you did not choose the alternatives.
This page is the complete reference for the design work that happens inside one component. It does not re-teach its neighbours: what architecture is and how it differs from design is on Software Architecture vs Software Design, the process of conceptual design and CRC cards is on The Design Process, abstraction, encapsulation and polymorphism are on Object-Oriented Modeling, the UML notation is on UML in Practice, coupling and cohesion in depth are on Design Quality, composition and the Law of Demeter are on Composing Objects, the smells that tell you a design went wrong are on Code Smells and Refactoring, and the five principles are on SOLID (SRP, OCP, LSP, ISP, DIP). Named patterns are on Design Patterns.
Page map
| If you are looking for | Go to |
|---|---|
| The whole chapter in a few tables | Everything in one minute |
| What LLD is and why it exists | Why LLD exists |
| Yourdon, Constantine, Wirfs-Brock, Larman, Meyer | Where it comes from |
| LLD vs HLD, and where LLD sits | LLD and where it sits |
| Structure charts, data-flow diagrams, top-down decomposition | Structured design |
| Structured vs object-oriented, side by side | Structured vs object-oriented |
| When functions and pipelines beat classes | When procedural wins |
| Roles and stereotypes: information holder, structurer, service provider, controller, coordinator, interfacer | Responsibility-driven design |
| Information expert, creator, low coupling, high cohesion | Assigning responsibilities (GRASP) |
| Association, aggregation, composition, dependency, inheritance, realization | Class relationships |
| Small interfaces, "accept interfaces, return structs", PHP interface plus final class | Interfaces and contracts |
| Command-query separation, parameter objects, return types, errors vs exceptions | Method design |
| Constructors that enforce invariants, validation at the boundary | State and invariants |
| Seams, dependency injection, clocks and randomness | Designing for testability |
| Maps vs slices, complexity awareness | Data structures at class level |
| Service-local models, DTOs, anti-corruption layer | LLD inside a microservice |
| clarify, entities, relationships, APIs, scenario, extend | The LLD interview method |
| Parking lot and notification system, complete | Solving the classic problems |
| Wrong beliefs, cheat sheet, self-check, every term | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The vocabulary. Every row is unpacked in the concepts section.
| Term | In plain words | Tiny example | What goes wrong without it |
|---|---|---|---|
| Low-level design (LLD) | Classes, functions, relationships and contracts inside one component | Lot, Ticket, FeePolicy for a parking service | Everyone codes their own idea of the structure |
| High-level design (HLD) | Components, data stores, protocols between them | "parking-api, billing, Postgres, Redis" | Components exist but nobody knows their shape |
| Structured design | Decompose by procedure; data and code are separate | A call tree of IssueTicket, fee, releaseSpot | Every procedure reaches into shared data |
| Object-oriented design | Decompose by responsibility; data and behaviour together | Lot owns its spots and guards its rules | God objects, or classes that are just records |
| Responsibility | Something an object knows, does, or decides | "Computes the fee for a stay" | Classes named after nouns but with no job |
| Role stereotype | A recurring kind of job | Controller, coordinator, service provider | Every class does a bit of everything |
| Relationship | How two classes are connected | Lot owns Spots | Hidden ownership, leaks, surprise deletes |
| Contract | What a method promises and requires | "Exit returns the fee or ErrUnknownTicket" | Callers guess; behaviour drifts |
| Invariant | A fact that is always true about an object | "A cart has at most 10 lines" | Invalid objects travel through the program |
| Seam | A place where behaviour can be swapped without editing code | Clock interface | Tests that sleep or depend on today's date |
The method in six lines (used by every worked problem on this page; see the interview method).
| Step | Question | Output |
|---|---|---|
| 1. Clarify | What must it do, for whom, how big, what is out of scope? | 5 to 8 requirements |
| 2. Entities | Which nouns carry state or rules? | A candidate class list |
| 3. Relationships | Who owns, uses, or implements whom? | A class diagram |
| 4. APIs | What are the public methods and their errors? | Signatures and contracts |
| 5. Scenario | Does one real request run through the design? | A sequence you can read aloud |
| 6. Extend | What happens when a rule or a channel is added? | Seams and a list of what changes |
Structured vs object-oriented in one table.
| Axis | Structured design | Object-oriented design |
|---|---|---|
| Unit of decomposition | Procedure (what happens) | Class (who is responsible) |
| Main picture | Structure chart, data-flow diagram | Class diagram, sequence diagram |
| Data | Passed around, often visible to all | Owned by the class that guards it |
| Variation | if/switch in the procedure | Polymorphism behind an interface |
| Strength | Pipelines, scripts, transformations | Long-lived rules with many variants |
| Weakness | Shared data couples everything | Needless classes for simple flows |
| Typical in | C, COBOL, shell, SQL scripts, Go main and handlers | Java, C#, PHP domain code, Go types with methods |
The six relationships.
| Relationship | UML mark | Go | PHP |
|---|---|---|---|
| Dependency | dashed arrow | parameter or local variable | method argument |
| Association | solid arrow | field holding a pointer or interface | private property set in the constructor |
| Aggregation | hollow diamond | []*B filled from outside | array of B passed in |
| Composition | filled diamond | []B created and owned inside | new B() inside the owner |
| Inheritance | solid line, hollow triangle | none; embed for reuse | extends |
| Realization | dashed line, hollow triangle | implicit method set | implements |
Why LLD exists
An architecture says "there is a parking service with a database and an API". It does not say what happens when two cars arrive for the last spot, who computes the fee, or where a new pricing rule goes. If nobody decides, each developer decides alone, and the structure that emerges is the sum of accidents. LLD is the cheap place to make those decisions: a diagram and a few signatures cost minutes; the same mistake in code, merged and used, costs weeks.
| Skipping LLD | Doing LLD |
|---|---|
| Fast start, first commit in an hour | One to two hours of thinking first |
| Structure is whatever the first feature needed | Structure follows the responsibilities |
| Every new rule edits many files | A new rule has an obvious home |
| Tests need the database and the clock | Pure rules are tested with fakes |
| Reviews argue about style | Reviews argue about responsibilities |
| Risk: tangled code that "works" | Risk: over-design for a throwaway script |
The picture shows the same parking-lot problem twice. On the left a structure chart: a call tree of procedures, with data flowing between them. On the right a class diagram: a Lot that owns its rules, two small interfaces, and a record. Neither is "right"; they answer different questions, and the rest of the page is about knowing which question you are asking.
The analogy we reuse on this page: building a house. The architect's site plan says where the house, garage and garden go (HLD). The electrician's drawing for one room says which circuit feeds which socket, where the fuse sits and what happens when a lamp blows (LLD). Without the plan, rooms collide; without the drawing, the electrician guesses. Neither drawing is the house.
Three common misunderstandings, up front
- "LLD means drawing UML before coding." LLD is deciding responsibilities and contracts. UML is one way to show the decision. A paragraph and five signatures can be a complete LLD.
- "Object-oriented design is better than structured design." They solve different shapes of problem. A data pipeline written as ten classes is worse than ten functions; a rule-heavy domain written as one 600-line procedure is worse than five cooperating classes.
- "An LLD interview wants the most patterns." It wants clear requirements, a small set of well-named classes, honest relationships, and a design that survives one extension. Naming five patterns you did not need loses points.
Where it comes from
Dijkstra, Wirth, early 1970s. Top-down decomposition and stepwise refinement came out of the structured-programming movement (Wirth's 1971 paper Program Development by Stepwise Refinement is the usual reference; we did not read it for this page). The idea: state the problem as one big step, then split each step into smaller steps until each is trivial to code.
Parnas, 1972. On the Criteria To Be Used in Decomposing Systems into Modules argued that modules should be cut around design decisions likely to change, not around the steps of a flowchart. That is the seed of information hiding and of every responsibility argument below (SRP tells the story in full).
Stevens, Myers and Constantine, 1974. Structured Design (IBM Systems Journal) gave us coupling and cohesion and a notation, the structure chart. The paper contrasts it with a flowchart: for modules A, B, C where A calls B which calls C, "To design A's interfaces properly, it is necessary to know that A is responsible for invoking B, but this is hard to determine from the flowchart." The structure chart shows who calls whom and which data crosses each call.
Yourdon and Constantine, 1979; DeMarco, 1979. The book Structured Design: Fundamentals of a Discipline of Computer Program and Systems Design (Yourdon and Constantine, 1979) turned the paper into a method. Tom DeMarco's Structured Analysis and System Specification (1979) added the data-flow diagram for the analysis side. Wikipedia summarises the pairing: "structure charts for structured design, and data-flow diagrams for structured analysis" (secondary source).
Meyer, late 1980s. Bertrand Meyer's Object-Oriented Software Construction introduced command-query separation (we read it through Martin Fowler's bliki entry, which credits Meyer).
Beck and Cunningham, 1989; Wirfs-Brock and Wilkerson, 1989. Class-Responsibility-Collaborator cards (OOPSLA 1989) and Object-Oriented Design: A Responsibility-Driven Approach (OOPSLA 1989) moved the question from "what data does a class hold" to "what is it responsible for, and whom does it ask for help". Rebecca Wirfs-Brock and Alan McKean's 2002 book Object Design: Roles, Responsibilities, and Collaborations names the role stereotypes used below (we read them through Wikipedia's summary, a secondary source).
Larman, 1990s. Craig Larman's Applying UML and Patterns collects nine GRASP principles ("General Responsibility Assignment Software Patterns"): information expert, creator, controller, low coupling, high cohesion, polymorphism, pure fabrication, indirection, protected variations. Wikipedia describes GRASP as "a set of nine fundamental principles in object design and responsibility assignment" (secondary source; the book was not read).
The Go idioms. The Go team's Code Review Comments wiki says: "Go interfaces generally belong in the package that uses values of the interface type, not the package that implements those values. The implementing package should return concrete (usually pointer or struct) types". The Go proverb "The bigger the interface, the weaker the abstraction" is one of the Go Proverbs Rob Pike gave in his Gopherfest SV 2015 talk (we read the proverbs page, not the video).
LLD interviews. Asking candidates to design a parking lot or an elevator on a whiteboard grew out of object-oriented design teaching and big-company hiring loops from the 2000s. There is no standard and no primary source; treat the method below as practice that works, not as a specification.
The concepts, one by one
Each block follows the same order: plain words, the usual wrong belief, a precise definition, a timeline, real scenarios, and the fix or the code.
LLD and where it sits Must-know
In plain words: HLD chooses the boxes (services, databases, queues). LLD opens one box and decides what is inside: the classes, what each is responsible for, and how they talk.
Common misunderstanding: "LLD is just class diagrams." The diagram is the output; the work is deciding responsibilities, relationships, method signatures, error behaviour and extension points.
Definition: SWEBOK v4 lists Detailed Design as its own stage of the Software Design KA, after architectural design; detailed design is what this page calls LLD. In practice: HLD ends at component boundaries and their interfaces; LLD begins inside a component and ends where a developer can write the code without a design meeting.
| HLD | LLD | |
|---|---|---|
| Scope | Whole system or service | One component or one use case |
| Units | Services, databases, queues, caches | Classes, functions, interfaces, packages |
| Questions | Scale, availability, data flow, protocols | Responsibilities, relationships, contracts, state |
| Artifacts | Architecture diagram, capacity numbers, API list | Class diagram, sequence diagram, signatures, invariants |
| Failure mode | Wrong boundaries, wrong data store | God classes, leaky abstractions, untestable code |
| Interview name | System design | Machine coding, OO design |
| Sibling chapters | System Design | This page |
Time Activity Who decides
1 W1 requirements, capacity, SLAs architect, product
2 W1 HLD: parking-api, billing, DB architect
3 W2 LLD: Lot, Spot, Ticket, FeePolicy developer or pair, reviewed
4 W2-3 code + tests developer
5 W4 review against the LLD teamReal scenario: a team builds a notification service. HLD picks "API, queue, workers, Redis". LLD decides "Dispatcher coordinates Channels; preferences and rate limiting are separate collaborators; security notices skip the limiter". Without that LLD, the workers become one 900-line if channel == ... function.
Fix: before coding any component larger than a day of work, write the one-page LLD: requirements, class list with one-line responsibilities, one diagram, public signatures, and one scenario.
Structured design: structure charts, DFDs, top-down decomposition Must-know
In plain words: you describe a program as the steps it performs. Each step is a module (a procedure). A big step breaks into smaller steps until each is easy. Data is a separate thing that flows between the steps.
Common misunderstanding: "Structured design is obsolete." The notation is dated, but the method is how we still write scripts, ETL jobs, request handlers, compilers and most Go main functions. Every main that parses, validates, computes and prints is a structure chart.
Definition: structured design (Stevens, Myers, Constantine 1974; Yourdon and Constantine 1979) designs a program as a hierarchy of modules and designs each module for low coupling and high cohesion. Its two pictures:
| Picture | Shows | Reads as | Used in |
|---|---|---|---|
| Structure chart | Modules as boxes, calls as lines, data and control passed on each call | Top calls bottom, left to right | Structured design |
| Data-flow diagram (DFD) | Processes, data stores, external entities and the flows between them; "no control flow, no decision rules and no loops" (Wikipedia) | Data goes in, is transformed, comes out | Structured analysis |
| Flowchart | Control flow, decisions, loops | Execution order | Algorithms |
| Data dictionary | Every data item and flow, defined | Lookup | Both |
Top-down functional decomposition (also stepwise refinement): start with one box ("Run the parking lot"), split it into the steps ("Enter", "Exit"), split each again, stop when a box is a few lines of code. Structured design adds the quality rules: each module should have one function (functional cohesion), pass simple data (data coupling), and the tree should be shallow and not too wide (the fan-out of a module should stay small).
Module coupling (from the 1974 paper, loosest to tightest): data, stamp, control, common, content. The full table with examples is on SRP and in Design Quality.
Step Structure-chart reading of "a car leaves"
1 1 ParkingApp calls Exit(ticketID, now)
2 2 Exit looks up the ticket record in Open (data couple: ticketID)
3 3 Exit calls releaseSpot(spots, spotID) (data couple: spot index)
4 4 Exit calls fee(entered, left) -> cents (data couple: two timestamps, one number back)
5 5 Exit deletes the ticket and returns centsReal scenario: a nightly billing script (read invoices, group by customer, compute VAT, write a CSV); a Go main that parses flags, loads config, starts a server; a Laravel Artisan command that imports a file; an ETL step in a data pipeline; a compiler pass.
Fix when it hurts: if many procedures reach into the same global record (common coupling), group the record and the procedures that guard it into one type. That is the step from structured to object-oriented design.
Object-oriented design: structured vs object-oriented Must-know
In plain words: instead of asking "what are the steps?", you ask "who is responsible for what?". Each class owns some data and the rules that protect it, and other classes ask it to do things.
Common misunderstanding: "OO means inheritance." Inheritance is one tool and often the wrong one. The core of OO design is assigning responsibilities and hiding data behind behaviour. Go has no inheritance and is still designed with objects, interfaces and responsibilities.
Definition: object-oriented design decomposes the system into objects that combine state and behaviour, communicate by messages (method calls) and are described by classes. Responsibility-driven design (below) is the most practical way to do it.
| Decision | Structured answer | Object-oriented answer |
|---|---|---|
| Where does the fee rule live? | Procedure fee(entered, left) | FeePolicy implementations |
| Where is the "taken" flag changed? | Any procedure that has the spot array | Only the Lot that owns the spots |
| Adding weekend pricing | Edit fee, add an if | Add a WeekendFee type, choose it at construction |
| Testing the fee | Call the function | Call the policy, no lot needed |
| Replacing the data store | Edit every procedure that touches it | Replace one collaborator |
| Reading the code | Follow the call tree | Follow the object collaborations |
Step Same change, "weekend rate", in both styles
1 S1 structured: edit fee(), add parameter weekend bool, edit IssueTicket and Exit to pass it
2 S2 structured: two callers, one shared record, retest everything that calls fee
3 O1 OO: add WeekendFee implementing FeePolicy
4 O2 OO: construct the Lot with WeekendFee on Saturdays; Lot is untouched
5 O3 OO: test WeekendFee alone; the Lot test is unchangedReal scenario: a billing domain with tariffs, discounts, taxes and exceptions per country is OO territory. A report generator that reads CSV and prints totals is structured territory.
Fix: pick per problem, and mix: OO for the long-lived rule-bearing core, plain functions for the transformations at the edges. Go and PHP both let you do this in one codebase.
When procedural or functional design wins Important
In plain words: if data comes in, gets transformed and goes out, with no long-lived state and few variants, write functions. Classes would only add ceremony.
Common misunderstanding: "Senior engineers always use classes and patterns." Seniors use the smallest structure that holds the rules. Go's standard library is mostly functions and small interfaces; strings, sort, bufio and io read like pipelines.
Definition: procedural design organises code as procedures over plain data; functional design adds "no hidden state, functions return new values". Prefer it when (a) the flow is a pipeline, (b) state is short-lived, (c) variation is a parameter and not a family of types, (d) the code is run once per request or per file.
| Situation | Better as | Why |
|---|---|---|
| Parse, filter, aggregate a file | Functions over slices | No state between steps; trivial to test |
| HTTP handler: decode, call, encode | Function plus small interfaces | One request, no object lifetime |
| Nightly ETL job | Function pipeline | Stages are independent and replaceable |
| Pricing with ten tariffs and exceptions | Classes behind an interface | Variants change independently |
| Long-lived stateful thing (lot, session, connection pool) | A type that guards its state | Invariants must live somewhere |
| Algorithms (sort, search, graph) | Functions, generics | No identity to model |
| Laravel report over a large table | Query builder, Collection or LazyCollection pipeline | The database already does the work |
Step Pipeline for "top 3 spenders", every step is a pure function
1 1 Parse(reader) -> []Record
2 2 Filter(records, valid) -> []Record
3 3 SumByUser(records) -> map[user]cents
4 4 TopN(sums, 3) -> []user
5 no struct, no state, four tests of four lines eachReal scenario: the Pipeline snippets below; sort.Slice taking a function; array_map and Collection::groupBy; a Laravel job that reads one S3 file and writes rows.
Fix: when a function grows a fourth boolean parameter or a long switch on a type that keeps growing, that is the signal to promote it to an interface with implementations.
Responsibility-driven design and role stereotypes Must-know
In plain words: design a class by asking "what does it know, what does it do, what does it decide?" and "who does it ask for help?". Then notice that most classes play one of a few familiar roles.
Common misunderstanding: "Find the nouns in the requirements and make them classes." Nouns give candidates, not a design. A noun with no responsibility (a Parking class with no behaviour) is a record. A responsibility with no noun (computing the fee) still needs a home.
Definition: Rebecca Wirfs-Brock and Brian Wilkerson's responsibility-driven design (1989) focuses on the contract of each object: the actions it is responsible for and the information it shares. A responsibility is either knowing (information it holds or can derive), doing (work it performs, or coordinating others) or deciding (rules it applies). A collaborator is another object it asks for help. In the 2002 book, Wirfs-Brock and McKean name role stereotypes; Wikipedia's summary reads "Role stereotypes are simplified roles that come with predefined responsibilities" (secondary source).
| Stereotype | Responsibility in one line | Parking lot example | Notification example | Smell if overdone |
|---|---|---|---|---|
| Information holder | Knows and provides information | Ticket, Money | Notification, Recipient | Anemic everything: all data, no rules |
| Structurer | Maintains relationships between objects | Lot's free-spot stacks and open-ticket map | The channel list in order | A structurer that also computes |
| Service provider | Performs work, offers a service | FeePolicy, HourlyFee | RateLimiter, one Channel | A service with hidden state |
| Controller | Makes decisions and directs others | The use-case that handles "car arrives" | The rule "security skips the limiter" | Controller knows every detail (God object) |
| Coordinator | Reacts to events by delegating | Lot.Enter calling stacks and clock | Dispatcher | Coordinator that also does the work |
| Interfacer | Transforms information and requests between parts | HTTP handler, PaymentGateway ACL | EmailChannel talking to SMTP | Business rules leaking into the adapter |
Wirfs-Brock further splits the interfacer into user interfacer (UI events), internal interfacer (between object neighbourhoods) and external interfacer (another application); and the information holder into holder and provider (the provider actively maintains the information).
Step CRC walk for "driver takes a ticket"
1 1 Interfacer (HTTP handler) receives POST /enter {size: small}
2 2 Controller (EnterParking) validates input, asks the Lot
3 3 Coordinator (Lot.Enter) asks its Structurer for the smallest free spot
4 4 Information holder (Ticket) is created with spot and time
5 5 Interfacer renders the ticket as JSONReal scenario: a Laravel app: PlaceOrderRequest (interfacer), PlaceOrder action (controller), OrderPricer (service provider), Order model (information holder with structure), Mail (external interfacer). A Go service: http.HandlerFunc (interfacer), service.Place (controller), pricing.Pricer (service provider), store.Orders (external interfacer).
Fix: write one line per class: "[role] responsible for [verb phrase]". If a class needs "and" twice, split it; if it has no verb, it is a record or it should disappear.
Assigning responsibilities: a GRASP pointer Important
In plain words: when you are unsure which class should do something, there are nine rules of thumb. The first one answers most cases: give the job to the class that already has the information.
Common misunderstanding: "GRASP is a list of patterns to apply." It is a set of questions for deciding where a method goes; "low coupling" and "high cohesion" are the yardsticks you check the answer against.
Definition: GRASP (Larman). Here are the nine, with the question each answers (the wording follows Wikipedia's summary of Larman; the pattern names are from the book).
| GRASP | Question | Short answer | Example here |
|---|---|---|---|
| Information expert | Who should do this? | The class that has the needed information | HourlyFee computes the fee: it owns the rates |
| Creator | Who creates object A? | The class that contains, records, closely uses, or has the data for A | Lot creates Tickets |
| Controller | Who receives a system event? | A non-UI object for the use case | EnterParking action |
| Low coupling | How to keep changes local? | Prefer few, one-way dependencies | Lot knows two small interfaces |
| High cohesion | How to keep classes focused? | Responsibilities that belong together | RateLimiter only limits |
| Polymorphism | How to handle variants by type? | Put the variation behind an interface | Channel, FeePolicy |
| Pure fabrication | What if no domain class fits? | Invent a service class | Dispatcher, Clock |
| Indirection | How to decouple two things? | Put a mediator between them | PaymentGateway between service and provider |
| Protected variations | How to shield from change? | Wrap the unstable point behind a stable interface | ACL around a provider API |
Step "Who computes the fee?" asked of GRASP
1 1 Information expert: who knows rates and the stay? FeePolicy (rates) + Ticket (times)
2 2 Low coupling: should Lot know rates? No: it holds a FeePolicy
3 3 Polymorphism: flat fee, hourly fee, weekend fee are variants -> interface
4 4 Result: Lot.Exit asks FeePolicy.Fee(size, stay); Lot never sees a rateFix: when stuck, run the list top to bottom; stop at the first answer that does not worsen coupling or cohesion. The principles' deeper treatment is on Design Quality and in SOLID.
Class relationships in code Must-know
In plain words: six ways one class can be connected to another, ordered from "briefly uses" to "is a kind of".
Common misunderstanding: "Aggregation and composition are different diagram arrows only." They encode ownership. The UML 2.5.1 specification says composite aggregation "requires a part object be included in at most one composite object at a time. If a composite object is deleted, all of its part instances that are objects are deleted with it." Aggregation (shared) has weaker semantics: "Precise semantics of shared aggregation varies by application area and modeler." Martin Fowler notes that the white diamond "has no semantics beyond that of a regular association", so many teams skip it.
Definition:
| Relationship | Lifetime | Meaning | Test | Go form | PHP form |
|---|---|---|---|---|---|
| Dependency | One call | "uses" | If B changes, A's method may break; A keeps no reference | func (r Report) Render(w io.Writer) | render(\Closure $write) |
| Association | Long, independent | "knows" | A has a field referring to B | customer *Customer | private readonly Customer $customer |
| Aggregation | Parts outlive whole | "has" (shared) | B is created elsewhere and passed in | members []*Person | array $members of passed-in objects |
| Composition | Parts die with whole | "owns" | A creates B and nobody else holds it | lines []Line built in AddLine | new Line(...) inside Order |
| Inheritance | Type hierarchy | "is a" | Every B can be used where A is expected (LSP) | not available; embed for reuse | class Circle extends Shape |
| Realization | Type to contract | "implements" | T provides all methods of I | implicit; var _ I = (*T)(nil) | class T implements I |
Step What the compiler and runtime do with each relationship (Go)
1 1 Realization: var _ Notifier = EmailNotifier{} -> build fails if a method is missing
2 2 Composition: Order.Lines() returns a copy -> callers cannot change the parts
3 3 Aggregation: Team.Add(p *Person) -> the team and the person have separate lifetimes
4 4 Embedding: Special{Base}.Describe() -> calls Base.Name, not Special.Name
5 5 Dependency: Report.Render(w io.Writer) -> nothing stored, nothing leakedReal scenario: an Order and its Lines (composition: delete the order, the lines go); a Team and Persons (aggregation); an Invoice that refers to a Customer (association); a service that formats a string through an injected Logger (dependency); EmailChannel implementing Channel (realization); Circle extending Shape (inheritance, in PHP).
Fix: prefer the weakest relationship that works: dependency over association, association over inheritance. Prefer composition over inheritance (the GoF book, chapter 1: class inheritance is "white-box reuse", object composition is the alternative); in Go this is the only option, and embedding is reuse, not subtyping: the embedded type's methods never call the outer type's overrides.
// Package relationships shows the six UML relationships as Go code.
package relationships
import (
"fmt"
"io"
)
// Realization: a type implements an interface by having its methods; no keyword.
type Notifier interface {
Notify(to, text string) error
}
type EmailNotifier struct{ From string }
func (e EmailNotifier) Notify(to, text string) error { return nil }
// Compile-time proof of the realization. It fails to build if the method set drifts.
var _ Notifier = EmailNotifier{}
// Dependency: Report uses an io.Writer only while Render runs. It keeps no reference.
type Report struct{ Title string }
func (r Report) Render(w io.Writer) error {
_, err := fmt.Fprintf(w, "# %s\n", r.Title)
return err
}
// Association: an Order knows its Customer. Both live on their own.
type Customer struct {
ID string
Name string
}
// Aggregation: a Team has Members, but members exist before and after the team.
type Person struct{ Name string }
type Team struct {
Name string
members []*Person // pointers to people created elsewhere
}
func (t *Team) Add(p *Person) { t.members = append(t.members, p) }
// Composition: an Order creates, owns and exposes its Lines only through copies.
type Line struct {
SKU string
Qty int
Cents int64
}
type Order struct {
customer *Customer // association
lines []Line // composition: lines die with the order
}
func NewOrder(c *Customer) *Order { return &Order{customer: c} }
func (o *Order) AddLine(sku string, qty int, cents int64) {
o.lines = append(o.lines, Line{SKU: sku, Qty: qty, Cents: cents})
}
// Lines hands out a copy so callers cannot change the composed parts.
func (o *Order) Lines() []Line { return append([]Line(nil), o.lines...) }
// Inheritance: Go has none. Embedding reuses code but does NOT dispatch virtually.
type Base struct{ name string }
func (b Base) Name() string { return b.name }
func (b Base) Describe() string { return "I am " + b.Name() } // always Base.Name
type Special struct{ Base }
func (s Special) Name() string { return "special " + s.name } // does not affect Base.Describe
// Describing a Special prints "I am x", not "I am special x".
func Demo() string { return Special{Base{name: "x"}}.Describe() }Designing interfaces and contracts Must-know
In plain words: an interface is the list of things a caller is allowed to ask for. Keep it short and let the caller define it, so the implementer is free to change.
Common misunderstanding: "Every class needs an interface, in case we want to swap it." An interface with one implementation and no consumer-side need is noise. The Go wiki says: "Do not define interfaces before they are used: without a realistic example of usage, it is too difficult to see whether an interface is even necessary, let alone what methods it ought to contain."
Definition: a contract is what a method promises (postconditions) and requires (preconditions), plus what it may fail with. Effective Go: "Interfaces with only one or two methods are common in Go code". The Go proverb says "The bigger the interface, the weaker the abstraction." In Go, "accept interfaces, return structs": the consumer package declares the small interface it needs; the producer returns a concrete type so new methods can be added "without requiring extensive refactoring" (Code Review Comments).
| Language | Idiom | Where the interface lives | Implementing it |
|---|---|---|---|
| Go | Small, consumer-defined interface; return concrete struct | In the package that uses it | Implicit; no implements |
| PHP | interface plus final class implementations; bind in the container | Next to the consumer (or in a Contracts namespace) | Explicit implements; final blocks extension |
| Laravel | Contracts in Illuminate\Contracts\*, bound in service providers | Framework or app namespace | bind or singleton in a provider |
| Java, C# | Interface per role, often one per service | With the implementation (default) | Explicit |
Step Why the consumer owns the interface
1 1 Greeter needs one thing: Find(ctx, id) (User, error)
2 2 Greeter declares userFinder with exactly that method
3 3 Store (concrete, returned by NewStore) already has Find, so it satisfies userFinder without importing Greeter
4 4 A test passes a three-line fakeFinder; no mocking library, no interface on the Store side
5 5 Store later gains Save, Delete, Count; Greeter is unaffectedReal scenario: io.Reader and io.Writer (one method each) are accepted by hundreds of functions; a Laravel PaymentGateway interface bound to StripeGateway in production and a fake in tests; a PHP final class repository that cannot be extended and mocked by subclassing, so tests use the interface.
Fix: write the interface at the call site, name it for what the caller needs (userFinder, not UserService), keep it to one to three methods, and add the compile-time check var _ I = (*T)(nil) where you want a build failure on drift.
// Package contracts shows "accept interfaces, return structs".
// The consumer declares the small interface it needs; the producer returns a concrete type.
package contracts
import (
"context"
"errors"
"fmt"
)
type User struct {
ID string
Name string
}
var ErrNotFound = errors.New("user not found")
// Store is the producer side. It returns and exposes concrete types only,
// so adding a method later breaks nobody.
type Store struct{ rows map[string]User }
func NewStore(users ...User) *Store {
s := &Store{rows: map[string]User{}}
for _, u := range users {
s.rows[u.ID] = u
}
return s
}
func (s *Store) Find(_ context.Context, id string) (User, error) {
u, ok := s.rows[id]
if !ok {
return User{}, ErrNotFound
}
return u, nil
}
func (s *Store) Save(_ context.Context, u User) error {
s.rows[u.ID] = u
return nil
}
// userFinder is the consumer side: one method, only what Greeter calls.
// Store satisfies it without knowing it exists.
type userFinder interface {
Find(ctx context.Context, id string) (User, error)
}
type Greeter struct{ users userFinder }
// NewGreeter accepts the interface and returns the struct.
func NewGreeter(users userFinder) *Greeter { return &Greeter{users: users} }
func (g *Greeter) Greet(ctx context.Context, id string) (string, error) {
u, err := g.users.Find(ctx, id)
if err != nil {
return "", fmt.Errorf("greet %s: %w", id, err)
}
return "Hello, " + u.Name, nil
}Method design Important
In plain words: a method should either change something or tell you something, take few arguments, and say clearly how it can fail.
Common misunderstanding: "Command-query separation means never return from a mutator." Meyer's rule has exceptions the author accepts; Fowler writes that "Popping a stack is a good example of a query that modifies state" and "I'm prepared to break it to get my pop"; the valuable idea is that you can use queries freely because they have no side effects. In concurrent code, "remove and return" must be one atomic step, so you keep it.
Definition: Fowler's summary of Meyer: "Queries: Return a result and do not change the observable state of the system (are free of side effects). Commands: Change the state of a system but do not return a value." Related habits:
| Habit | Rule | Go | PHP | Why |
|---|---|---|---|---|
| Command-query separation | A method is a command or a query | Drop() vs Peek() | drop() vs peek() | Queries are safe to call anywhere |
| Parameter object | Group arguments that travel together | SearchParams struct | readonly class SearchParams | Named, validated, extensible (Fowler: Introduce Parameter Object) |
| No boolean flags | Two behaviours, two methods or two types | Render and RenderPDF | same | A flag means two jobs |
| Return type honesty | Return what you mean | (T, error), (T, bool) | ?T, T or throw | Callers cannot ignore absence |
| Failure as value (Go) | Return error, wrap with %w | errors.Is, errors.As | n/a | Explicit control flow |
| Failure as exception (PHP) | Throw domain exceptions, catch at the boundary | n/a | throw new OutOfStock | Keeps the happy path clean |
| Context first (Go) | ctx context.Context is the first parameter | Search(ctx, p) | n/a | Cancellation and deadlines |
| Few parameters | Three or fewer; more means an object | NewLot(cap, fees, clock) | constructor promotion | Readability |
Step Calling the same query twice vs the same command twice
1 1 Peek(); Peek() -> same answer, nothing changed
2 2 Drop(); Drop() -> two items removed
3 3 Pop(); Pop() -> two items removed AND two answers; one atomic step
4 4 rule: queries are idempotent and free; commands need thought; Pop is the accepted exceptionError handling design in depth (when to return, wrap, retry or panic; exceptions vs error values across layers) is on Error and Exception Handling; this page only fixes the habit that a contract names its failures.
Real scenario: Lot.Enter returns a Ticket and an error: command and query together, accepted because issuing and returning one ticket must be atomic; a SearchParams object replacing search($q, $from, $to, $limit, $cursor, $sort, $asc).
Fix: if two callers pass the same three arguments in the same order, make them an object; if a method has a boolean parameter, split it.
// Package methods shows method-design habits: command-query separation,
// parameter objects, honest return types.
package methods
import (
"context"
"errors"
"time"
)
// Stack separates commands (Push, Drop) from queries (Peek, Len).
type Stack[T any] struct{ items []T }
func (s *Stack[T]) Push(v T) { s.items = append(s.items, v) }
// Peek is a query: it changes nothing. ok is false for an empty stack.
func (s *Stack[T]) Peek() (v T, ok bool) {
if len(s.items) == 0 {
return v, false
}
return s.items[len(s.items)-1], true
}
// Drop is a command: it removes the top and returns nothing.
func (s *Stack[T]) Drop() { s.items = s.items[:max(0, len(s.items)-1)] }
func (s *Stack[T]) Len() int { return len(s.items) }
// Pop is Meyer's famous exception: remove-and-return must be one atomic step.
func (s *Stack[T]) Pop() (v T, ok bool) {
v, ok = s.Peek()
if ok {
s.Drop()
}
return v, ok
}
// SearchParams is a parameter object: named fields instead of six positional arguments.
type SearchParams struct {
Query string
From, To time.Time
Limit int
Cursor string
}
type Hit struct{ ID, Title string }
var ErrBadParams = errors.New("methods: bad search params")
// Validate keeps the rules next to the data they guard.
func (p SearchParams) Validate() error {
if p.Query == "" || p.Limit < 1 || p.Limit > 100 {
return ErrBadParams
}
if !p.To.IsZero() && p.To.Before(p.From) {
return ErrBadParams
}
return nil
}
// Search takes the parameter object; ctx stays a separate first argument by Go convention.
// The result is (value, error): expected failures are values, not panics.
func Search(ctx context.Context, p SearchParams) ([]Hit, error) {
if err := p.Validate(); err != nil {
return nil, err
}
if err := ctx.Err(); err != nil {
return nil, err
}
return []Hit{{ID: "1", Title: p.Query}}, nil
}State and invariants Must-know
In plain words: an invariant is something that must always be true about an object ("a cart has at most 10 lines", "money is never negative"). Build objects so they cannot start or become invalid.
Common misunderstanding: "Validate in the controller and everything inside is safe." The controller is one door; jobs, commands, tests and other services are others. Put the rule in the constructor and the methods that change state, so every door goes through it.
Definition: an invariant is a condition that holds after construction and after every public method. The constructor (or a named factory: NewMoney, ParseEmail, PHP new Money(...)) establishes it; every mutator preserves it; fields are unexported (Go) or private/readonly (PHP) so nobody else can break it. Validation at the boundary (HTTP input, CSV rows, queue messages) turns untrusted data into a valid object once; inside, code trusts the type.
| Technique | Go | PHP 8.4 | Notes |
|---|---|---|---|
| Constructor that validates | func NewMoney(c int64, cur string) (Money, error) | __construct throws InvalidArgumentException | Go returns the error; PHP throws |
| Unexported fields | lowercase fields | private or readonly properties | Package-level privacy in Go |
| Immutability | value receiver returning a new value | final readonly class | Safer to share, no defensive copy |
| Zero-value strategy | Make the zero value useful or unrepresentable | Typed properties without default are uninitialised | var m Money should not be a valid amount by accident |
| Enums for closed sets | named int type with constants | enum Size: int | Illegal states impossible |
| Boundary validation | decode, then construct | Form Request, then new Email(...) | Rules once at the edge |
| Database mirror | CHECK, UNIQUE, partial index | same | Last line of defence, concurrency-proof |
Step Where an invalid object is stopped
1 1 HTTP body {"email": " Sara@Example.COM "} arrives
2 2 Form Request / decoder checks shape and type (boundary validation)
3 3 ParseEmail trims, lower-cases, checks format -> Email{"sara@example.com"}
4 4 Inside the service, every Email is valid; no re-checks, no null checks
5 5 users.email has UNIQUE and CHECK; a race still cannot insert a duplicateReal scenario: Money that refuses negative amounts and mixed currencies; a Cart that refuses an 11th line; a Lot that refuses zero spots; an Order that cannot be paid twice.
Fix: "make illegal states unrepresentable": enums over strings, constructors over setters, immutability over defensive copies.
// Package invariants shows constructors that make invalid objects impossible to build.
package invariants
import (
"errors"
"fmt"
"net/mail"
"strings"
)
// Email can only be created through ParseEmail, so every Email in the program is valid.
type Email struct{ addr string }
func ParseEmail(s string) (Email, error) {
a, err := mail.ParseAddress(strings.TrimSpace(s))
if err != nil {
return Email{}, fmt.Errorf("invalid email: %w", err)
}
return Email{addr: strings.ToLower(a.Address)}, nil
}
func (e Email) String() string { return e.addr }
// Money is an amount in minor units with a currency; amounts never go negative.
type Money struct {
cents int64
currency string
}
var ErrCurrencyMismatch = errors.New("currency mismatch")
func NewMoney(cents int64, currency string) (Money, error) {
if cents < 0 {
return Money{}, errors.New("money cannot be negative")
}
if len(currency) != 3 {
return Money{}, errors.New("currency must be a 3-letter code")
}
return Money{cents: cents, currency: strings.ToUpper(currency)}, nil
}
func (m Money) Cents() int64 { return m.cents }
func (m Money) Currency() string { return m.currency }
// Add returns a new value; Money is immutable.
func (m Money) Add(o Money) (Money, error) {
if m.currency != o.currency {
return Money{}, ErrCurrencyMismatch
}
return Money{cents: m.cents + o.cents, currency: m.currency}, nil
}
// Cart protects the rule "at most 10 lines, quantity 1..99" inside its methods.
type Cart struct{ lines map[string]int }
func NewCart() *Cart { return &Cart{lines: map[string]int{}} }
func (c *Cart) Add(sku string, qty int) error {
if qty < 1 || qty > 99 {
return fmt.Errorf("quantity %d out of range 1..99", qty)
}
if _, exists := c.lines[sku]; !exists && len(c.lines) >= 10 {
return errors.New("cart is limited to 10 distinct lines")
}
c.lines[sku] += qty
return nil
}
func (c *Cart) Quantity(sku string) int { return c.lines[sku] }Designing for testability Must-know
In plain words: a class is easy to test when everything it depends on is handed to it, including the clock and random numbers. Hidden dependencies (time.Now(), new Mailer() inside a method) make tests slow and flaky.
Common misunderstanding: "To test it, mock everything." Mocks of every collaborator test the mocks. The Go wiki: "Do not define interfaces on the implementor side of an API 'for mocking'; instead, design the API so that it can be tested using the public API of the real implementation." Use fakes at real seams (time, network, database), real objects elsewhere.
Definition: a seam (a term from Michael Feathers' Working Effectively with Legacy Code, not read for this page) is a place where you can change behaviour without editing the code there. Dependency injection supplies collaborators from outside: constructor injection first. Time and randomness are dependencies like any other.
| Hidden dependency | Seam | Go | PHP / Laravel |
|---|---|---|---|
| Current time | Clock interface | Now() time.Time, fakeClock | Clock interface, or travelTo() and freezeTime() in tests |
| Randomness | Function value | type IntN func(n int) int | Closure or a Randomizer interface |
| Database | Repository interface | consumer-side userFinder | interface bound in a provider; or an in-memory fake |
| HTTP call | Small client interface | Doer with Do(req) | Http::fake() |
| Mail, SMS | Channel interface | fake channel counting sends | Notification::fake(), Mail::fake() |
| Global state | Constructor parameter | pass the config struct | config() read in the provider, not in the domain |
| IDs | IDGenerator function | func() string | Str::uuid() behind an interface |
Step Test of "session expires after 30 minutes"
1 1 c := &fakeClock{now: 12:00}
2 2 s := StartSession(c, 30*time.Minute)
3 3 s.Expired() -> false
4 4 c.now = 12:30 (no sleep)
5 5 s.Expired() -> true (the test takes microseconds, not 30 minutes)Real scenario: a token that expires after 15 minutes; a rate limiter refilling at one token per second; a "lottery winner" picker; a nightly job that decides "yesterday" from the clock.
Fix: inject Clock through the constructor (Go) or the container (Laravel), never call time.Now() or now() inside domain logic. Laravel's travelTo and freezeTime are fine for feature tests that exercise the whole framework. The depth on dependency inversion is on DIP.
// Package testability treats time and randomness as dependencies,
// so tests can control them.
package testability
import (
"math/rand/v2"
"time"
)
// Clock is the seam for "what time is it". Production uses SystemClock.
type Clock interface{ Now() time.Time }
type SystemClock struct{}
func (SystemClock) Now() time.Time { return time.Now() }
// Session expires after a fixed time to live. It never calls time.Now itself.
type Session struct {
clock Clock
ttl time.Duration
started time.Time
}
func StartSession(c Clock, ttl time.Duration) *Session {
return &Session{clock: c, ttl: ttl, started: c.Now()}
}
func (s *Session) Expired() bool { return !s.clock.Now().Before(s.started.Add(s.ttl)) }
// IntN is the seam for randomness: a function value is the smallest possible interface.
type IntN func(n int) int
// Pick returns one of the items. Production passes rand.IntN; a test passes a constant.
func Pick[T any](items []T, intn IntN) T { return items[intn(len(items))] }
// Production wiring, in one place:
var _ IntN = rand.IntNData structures and algorithms at class level Important
In plain words: inside a class, the choice between a slice and a map is a design decision. It decides whether a lookup is a quick jump or a scan of everything.
Common misunderstanding: "Premature optimisation is evil, so use whatever." The warning against premature optimisation is about micro-tuning. Choosing O(1) lookup by ID over an O(n) scan of a slice is design, not optimisation, and the first is as easy to write as the second.
Definition: for each public operation of a class, state the expected cost in terms of its collections, and pick the structure that makes the frequent operation cheap.
| Need | Structure | Cost | Go | PHP |
|---|---|---|---|---|
| Find by ID | Hash map | O(1) average | map[TicketID]entry | array<string, Ticket> |
| Ordered iteration, small n | Slice | O(n) scan, cache-friendly | []Channel | list<Channel> |
| Take the latest free item | Stack (slice used as LIFO) | O(1) push and pop | free[size] stack | array_pop |
| Smallest or largest first | Heap | O(log n) | container/heap | SplHeap, SplPriorityQueue |
| Membership test | Set (map[T]struct{}) | O(1) average | map[string]struct{} | array_key_exists, isset |
| Sliding window, FIFO | Queue, ring buffer | O(1) | slice with head index | SplQueue |
| Sorted range queries | Sorted slice plus binary search | O(log n) search, O(n) insert | sort.Search | array + custom |
| Rate limiting per key | Map of token buckets | O(1) per call | map[string]*bucket | cache keys (RateLimiter) |
Step Parking lot, "find the smallest free spot that fits"
1 1 naive: scan all 5,000 spots per arrival -> O(n)
2 2 better: one stack of free spots per size (3 stacks) -> O(sizes) = O(3)
3 3 exit: push the spot back on its stack -> O(1)
4 4 "where is ticket T7?": map lookup instead of scanning open tickets -> O(1)
5 5 cost of the choice: the lot must keep the stacks and the map consistent (an invariant)Real scenario: the lot's free stacks and open map; the notification RateLimiter's map of buckets (memory grows with users: evict idle ones in production); a leaderboard that needs a heap or a sorted structure; deduplication with a set.
Fix: write the cost next to the method in a comment ("O(1)"), and keep the indexes private so only the class can keep them consistent. Concurrency in these structures (mutexes, channels) is on Designing for Concurrency.
LLD inside a microservice Important
In plain words: inside one service you design the same way, but the service's model is private, the wire format is a separate thing, and anything foreign is translated at the edge.
Common misunderstanding: "One shared User class for all services keeps things consistent." A shared model couples releases and leaks one team's decisions into every other service. Each service owns a model that fits its job; contracts between services are messages or API schemas.
Definition:
| Concept | Meaning | Rule |
|---|---|---|
| Service-local model | The domain classes inside one service | Never exported as a shared library |
| DTO (Data Transfer Object) | A flat structure for the wire or a boundary | No behaviour; mapped to and from the model |
| Mapper / translator | Code that converts DTO to model | One place per boundary |
| Anti-corruption layer (ACL) | Translator plus gateway that shields the model from a foreign model | "This layer translates communication between the two systems" (Azure Architecture Center) |
| Published contract | OpenAPI, protobuf, message schema | Versioned; backward compatible |
| Domain events | Facts the service publishes | Past tense, small, stable |
Step Payment provider reply crossing the ACL
1 1 provider returns {"charge_id":"ch_1","amount":"12.50","ccy":"EUR","status":3}
2 2 providerGateway.Charge calls the provider with its own DTO (providerCharge)
3 3 toPayment maps amount "12.50" -> 1250 cents, status 3 -> Review
4 4 unknown status 9 -> ErrUnknownStatus (fail loudly, never guess)
5 5 the rest of the service sees Payment{Cents: 1250, Status: Review} onlyReal scenario: an orders service that calls a payment provider, a legacy ERP, and a shipping API, each with its own vocabulary; a Laravel API Resource that shapes an Eloquent model into a response DTO.
Fix: one package or namespace per foreign system; the rest of the service imports only the interface and domain types. DDD names this and the integration patterns on Context Maps and Integration Patterns; the call-boundary rules are on Service Communication.
// Package acl shows an anti-corruption layer inside one service: the provider's
// shape stays in this file, and the rest of the service sees only domain types.
package acl
import (
"errors"
"fmt"
"strconv"
)
// providerCharge mirrors the external payment provider's JSON. It never leaves this package.
type providerCharge struct {
ChargeID string `json:"charge_id"`
Amount string `json:"amount"` // decimal string such as "12.50"
Ccy string `json:"ccy"`
Status int `json:"status"` // 0 pending, 1 ok, 2 declined, 3 3-ds required
}
// Status, Payment and the errors are the service's own language.
type Status string
const (
Pending Status = "pending"
Paid Status = "paid"
Declined Status = "declined"
Review Status = "needs_review"
)
type Payment struct {
ID string
Cents int64
Currency string
Status Status
}
var ErrUnknownStatus = errors.New("acl: unknown provider status")
// toPayment is the translator: the only place that knows how the provider spells things.
func toPayment(c providerCharge) (Payment, error) {
cents, err := decimalToCents(c.Amount)
if err != nil {
return Payment{}, fmt.Errorf("charge %s: %w", c.ChargeID, err)
}
st, ok := map[int]Status{0: Pending, 1: Paid, 2: Declined, 3: Review}[c.Status]
if !ok {
return Payment{}, fmt.Errorf("charge %s: %w (%d)", c.ChargeID, ErrUnknownStatus, c.Status)
}
return Payment{ID: c.ChargeID, Cents: cents, Currency: c.Ccy, Status: st}, nil
}
func decimalToCents(s string) (int64, error) {
f, err := strconv.ParseFloat(s, 64)
if err != nil {
return 0, fmt.Errorf("bad amount %q: %w", s, err)
}
return int64(f*100 + 0.5), nil
}
// Gateway is what the rest of the service depends on: a domain-shaped interface.
type Gateway interface {
Charge(customerID string, cents int64, currency string) (Payment, error)
}
// ProviderGateway adapts a raw provider call to the Gateway contract.
type ProviderGateway struct {
call func(customerID, amount, ccy string) (providerCharge, error)
}
func NewProviderGateway(call func(customerID, amount, ccy string) (providerCharge, error)) *ProviderGateway {
return &ProviderGateway{call: call}
}
func (g *ProviderGateway) Charge(customerID string, cents int64, currency string) (Payment, error) {
amount := fmt.Sprintf("%d.%02d", cents/100, cents%100)
raw, err := g.call(customerID, amount, currency)
if err != nil {
return Payment{}, err
}
return toPayment(raw)
}
var _ Gateway = (*ProviderGateway)(nil)The LLD interview method
Must-know An LLD interview (also "machine coding" or "object-oriented design round") gives you 45 to 90 minutes and a vague prompt ("design a parking lot"). The method below also works for real work, because it is just LLD done out loud.In plain words: ask what is wanted, list the nouns that carry rules, say who owns whom, write the public methods, walk one real request through, then show what happens when a requirement is added.
Common misunderstanding: "Start by drawing classes." Start by clarifying; a diagram built on a wrong assumption is worth nothing, and interviewers grade the questions you ask.
| Step | Minutes (of 45) | What you do | What you say | Output |
|---|---|---|---|---|
| 1. Clarify | 5 | Ask about actors, scale, rules, out of scope | "Is it one lot or many? Do vehicles have sizes? Is payment in scope?" | A numbered requirements list |
| 2. Entities | 5 | Underline nouns; keep those with state or rules; drop the rest | "Lot, Spot, Ticket, Size; payment is a FeePolicy" | Candidate classes |
| 3. Relationships | 8 | Decide ownership and direction; mark interfaces | "Lot owns Spots (composition) and depends on FeePolicy" | Class diagram |
| 4. APIs | 8 | Write signatures and the errors each may return | "Enter(size) (Ticket, error); ErrFull" | Method list |
| 5. Walk a scenario | 10 | Run one happy path and one failure through the design | "Car arrives, lot full, small car takes a medium spot..." | Spoken sequence |
| 6. Extend | 7 | Add a requirement; show where it plugs in | "Weekend pricing is a new FeePolicy; the lot is unchanged" | Seams and trade-offs |
| 7. Wrap up | 2 | State trade-offs, concurrency, persistence, what you skipped | "In-memory here; a unique index makes it safe across nodes" | Honest limits |
Min Interview timeline for "design a parking lot"
1 0 prompt: "design a parking lot"
2 2 candidate: scale? sizes? payment? one entrance? multiple floors?
3 6 entities: Lot, Spot, Ticket, Size, FeePolicy, Clock
4 12 relationships: Lot owns Spots (composition), Lot uses FeePolicy and Clock (association to interface)
5 20 APIs: Enter, Exit, Free; ErrFull, ErrUnknownTicket
6 28 scenario: A arrives, B arrives, lot full, A leaves, C enters; check the stacks
7 38 extend: weekend pricing, EV spots, multiple floors; point at seams
8 43 limits: concurrency (mutex), persistence (unique index), what is not builtWhat interviewers look for: requirements asked, not assumed; names that say what things are; small classes with one responsibility each; interfaces where behaviour varies; a clear error story; a design that survives one extension without edits to existing classes (the open-closed idea from OCP); awareness of concurrency and persistence even if you do not build them.
Common traps: designing for scale you were not asked about; patterns for their own sake (a Factory of one thing); modelling every noun as a class; ignoring errors; forgetting that two threads can enter at once; a Manager or Handler class that does everything.
Real scenario: the two worked problems in Solving the classic problems follow exactly this order; the same order works for an elevator, a library, a chess game, a vending machine, a ride-sharing dispatcher, a rate limiter, a logger framework, an LRU cache.
Fix when stuck: go back to responsibilities: "who knows this?", "who does this?", "who decides this?" and write one line per class.
Per-language and per-framework view
| Language or framework | Unit of design | Interfaces | Inheritance | Errors | Natural LLD style |
|---|---|---|---|---|---|
| Go | Package, then type with methods | Implicit, small, consumer-owned | None; embedding for reuse | error values, errors.Is/As | Small types, plain functions, interfaces at seams |
| PHP 8.4 | Class in a namespace | interface, explicit | extends, abstract, final | Exceptions | Value objects, services, enums, readonly classes |
| Laravel 13 | Framework slots (Action, Request, Policy, Job, Notification) | Contracts bound in the container | Models extend Eloquent; avoid elsewhere | Exceptions plus the exception handler | Thin slots around domain classes |
| Java | Class in a package | Explicit, often one per service | Common, shallow is better | Checked and unchecked exceptions | Class-per-role, builders, DI frameworks |
| C# | Class in a namespace | Explicit | Common | Exceptions | Same as Java, records for DTOs |
| Python | Module, class | Protocols or ABCs | Multiple inheritance possible | Exceptions | Dataclasses plus functions |
| TypeScript | Module, class, type | Structural types | extends | Exceptions or result types | Types and functions over class hierarchies |
| C, COBOL, shell | Procedure, file | Header files | None | Return codes | Structured design in its pure form |
Go. The package is the design unit; a type earns methods when it guards state. Interfaces are small and live with the consumer; constructors named NewX return *X and an error when the object can be invalid. Embedding gives code reuse, not substitutability.
PHP and Laravel. Make value objects final readonly; put interfaces next to the consumer or in a Contracts namespace; bind them in a service provider; keep controllers thin and put the rules in plain classes that need no framework to test. Notification, Mailable and Job are already LLD decisions made for you (a "channel list", a "message", a "unit of queued work"); use them before inventing your own.
Mechanics
The responsibility table Must-know
A CRC card (class, responsibility, collaborators; see The Design Process) in table form. Fill it for every candidate class; any row without a verb or with two unrelated verbs needs work.
| Class | Role | Responsibilities (verbs) | Collaborators | Knows (state) |
|---|---|---|---|---|
Lot | Coordinator + structurer | Allocate a spot, release a spot, issue a ticket, report free count | FeePolicy, Clock, spot | Free stacks, open tickets |
Ticket | Information holder | Carry id, spot and entry time | none | Id, spot, time |
FeePolicy | Service provider | Compute a fee for a stay | none | Rates |
Clock | Service provider | Tell the time | none | none |
Dispatcher | Coordinator | Choose channels, apply rate limit, fall back | Channel, Preferences, RateLimiter | Channel order |
Channel | Service provider / external interfacer | Deliver one message | SMTP, SMS gateway | Credentials |
RateLimiter | Service provider | Allow or deny per key | Clock | Buckets |
Preferences | Information provider | Answer "may I send this?" | database | User settings |
Checking a design: the five questions Must-know
| Question | Pass | Fail signal | Repair |
|---|---|---|---|
| Can each class be described in one sentence without "and"? | "Computes fees" | "Computes fees and sends receipts" | Split |
| Can I test it with fakes only at the edges? | Lot with fakeClock | Needs database to test a rule | Extract the rule, inject the store |
| Does a new variant add a class instead of editing one? | WeekendFee | New if in fee() | Interface plus implementation |
| Does a change stay local? | One file | Shotgun surgery | Move the responsibility (Move Method) |
| Is state guarded by one owner? | Lot alone edits spots | Several classes flip taken | Encapsulate, narrow the API |
Walking a scenario Must-know
Step Scenario: lot has 1 small + 1 medium spot. A small car, then another small car, then a third.
1 t0 Enter(Small) -> pops spot 1 (small) -> Ticket T1 (spot 1)
2 t1 Enter(Small) -> small stack empty, falls through to Medium -> pops spot 2 -> Ticket T2 (spot 2)
3 t2 Enter(Small) -> both stacks empty -> ErrFull
4 t3 Exit(T2) -> entry holds spot 2 (size Medium) -> pushed to the Medium stack; fee from FeePolicy
5 t4 Exit(T2) -> not in open map -> ErrUnknownTicket
6 t5 Free(Medium) -> 1If a step surprises you, the design has a gap. In this walk the entry{ticket, spot} type exists because the first draft stored only the ticket and could not return a small car's medium spot to the right stack.
Cost of operations Important
| Operation | Parking Lot | Notification Dispatcher | Why |
|---|---|---|---|
| Create | O(spots) once | O(channels) once | Constructors do the setup |
| Main action | Enter: O(sizes), here at most 3 | Send: O(channels) | Stacks and a short list |
| Release | Exit: O(1) | n/a | Map lookup plus push |
| Query | Free: O(1) | n/a | len of a slice |
| Memory | O(spots + open tickets) | O(users) for buckets | Evict idle buckets in production |
| Concurrency | One mutex around the lot | One limiter per process | Contention is the first scaling limit |
Go
Example: structured and pipeline style
The structure chart from the diagram, written as Go: records plus procedures.
// Package structured solves the parking-lot problem the structured-design way:
// plain data records, and procedures that take the data they work on.
// There is no object that owns behaviour; the structure chart is the call tree
// IssueTicket -> findFreeSpot, Exit -> fee, releaseSpot.
package structured
import (
"errors"
"strconv"
"time"
)
// Spot, Ticket and Lot are records: data only, every field visible.
type Spot struct {
ID int
Size int // 1 small, 2 medium, 3 large
Taken bool
}
type Ticket struct {
ID string
SpotID int
EnteredAt time.Time
}
type Lot struct {
Spots []Spot
Open map[string]Ticket
NextID int
}
var (
ErrFull = errors.New("lot is full")
ErrUnknownTicket = errors.New("unknown ticket")
)
// IssueTicket is the top module of the "enter" branch of the structure chart.
func IssueTicket(lot *Lot, vehicleSize int, now time.Time) (Ticket, error) {
idx, ok := findFreeSpot(lot.Spots, vehicleSize)
if !ok {
return Ticket{}, ErrFull
}
lot.Spots[idx].Taken = true
lot.NextID++
t := Ticket{ID: "T" + strconv.Itoa(lot.NextID), SpotID: lot.Spots[idx].ID, EnteredAt: now}
lot.Open[t.ID] = t
return t, nil
}
// findFreeSpot is a subordinate module: it returns the smallest free spot that fits.
func findFreeSpot(spots []Spot, size int) (int, bool) {
best := -1
for i, s := range spots {
if s.Taken || s.Size < size {
continue
}
if best == -1 || s.Size < spots[best].Size {
best = i
}
}
return best, best != -1
}
// Exit is the top module of the "leave" branch.
func Exit(lot *Lot, ticketID string, now time.Time) (int64, error) {
t, ok := lot.Open[ticketID]
if !ok {
return 0, ErrUnknownTicket
}
releaseSpot(lot.Spots, t.SpotID)
delete(lot.Open, ticketID)
return fee(t.EnteredAt, now), nil
}
func releaseSpot(spots []Spot, spotID int) {
for i := range spots {
if spots[i].ID == spotID {
spots[i].Taken = false
return
}
}
}
// fee is data in, data out: 200 cents per started hour.
func fee(entered, left time.Time) int64 {
hours := int64(left.Sub(entered)/time.Hour) + 1
return hours * 200
}And a pipeline where plain functions are the right design:
// Package pipeline shows a problem where plain functions beat objects:
// read records, filter them, aggregate them. Data goes in, data comes out,
// no state lives between the steps.
package pipeline
import (
"bufio"
"fmt"
"io"
"sort"
"strconv"
"strings"
)
type Record struct {
User string
Cents int64
}
// Parse turns "alice,1250" lines into records.
func Parse(r io.Reader) ([]Record, error) {
var out []Record
sc := bufio.NewScanner(r)
for line := 1; sc.Scan(); line++ {
user, amount, ok := strings.Cut(sc.Text(), ",")
if !ok {
return nil, fmt.Errorf("line %d: want user,cents", line)
}
cents, err := strconv.ParseInt(strings.TrimSpace(amount), 10, 64)
if err != nil {
return nil, fmt.Errorf("line %d: %w", line, err)
}
out = append(out, Record{User: strings.TrimSpace(user), Cents: cents})
}
return out, sc.Err()
}
// Filter keeps the records for which keep returns true.
func Filter(rs []Record, keep func(Record) bool) []Record {
var out []Record
for _, r := range rs {
if keep(r) {
out = append(out, r)
}
}
return out
}
// SumByUser aggregates with a map: O(n) time, O(users) memory.
func SumByUser(rs []Record) map[string]int64 {
sums := make(map[string]int64, len(rs))
for _, r := range rs {
sums[r.User] += r.Cents
}
return sums
}
// TopN sorts the keys by total, largest first, and returns at most n of them.
func TopN(sums map[string]int64, n int) []string {
users := make([]string, 0, len(sums))
for u := range sums {
users = append(users, u)
}
sort.Slice(users, func(i, j int) bool {
if sums[users[i]] != sums[users[j]] {
return sums[users[i]] > sums[users[j]]
}
return users[i] < users[j]
})
if len(users) > n {
users = users[:n]
}
return users
}The Go angle
- No classes, no inheritance. A type with methods is the class; an interface is the contract; embedding is reuse. LLD in Go is "which types, which methods, which small interfaces".
- The package is the unit of design. Export only what callers need; put helpers in
internal/(SRP covers it). Name packages for what they provide (parking,notify), notutilsorcommon. - Constructors and invariants.
NewLot(...) (*Lot, error)returns an error if the object would be invalid; unexported fields stop outside code from breaking it. "Make the zero value useful" (Go Proverbs) where you can, and make invalid states unrepresentable where you cannot. - Accept interfaces, return structs.
NewGreeter(users userFinder) *Greeter. The interface is private to the consumer. - Errors are values. Return
error, define sentinels (ErrFull) for expected cases, wrap with%w, test witherrors.Is. See Error and Exception Handling. - Concurrency inside a type. A
sync.Mutexfield next to the data it guards is part of the design; document which methods are safe to call concurrently. - Tooling that checks LLD.
go vet,staticcheck(unused code, misuse),go test -race,go doc(read your public API as a stranger would). - Standard library as a teacher.
io.Reader/io.Writer(one method),sort.Interface,http.Handler,database/sql(a concrete*sql.DBplusdriverinterfaces behind it).golang.org/x/time/rateis a token-bucketLimiter: "a token bucket of size b, initially full and refilled at rate r tokens per second", created withrate.NewLimiter(rate.Every(time.Second), 5)and used throughAllow,AllowN,Wait.
Laravel
Example: the same ideas in PHP 8.4
Structured style first (functions over arrays), then the pipeline with Collection:
<?php
// Structured style: plain data arrays and procedures that take the data they work on.
// The structure chart is the call tree: issueTicket -> findFreeSpot, exitLot -> fee, releaseSpot.
// Fine for a script or a pipeline; here it shows what the OO version replaces.
namespace App\Parking\Structured;
use RuntimeException;
function issueTicket(array &$lot, int $vehicleSize, int $now): array
{
$index = findFreeSpot($lot['spots'], $vehicleSize);
if ($index === null) {
throw new RuntimeException('lot is full');
}
$lot['spots'][$index]['taken'] = true;
$ticket = ['id' => 'T'.(++$lot['next_id']), 'spot_id' => $lot['spots'][$index]['id'], 'entered_at' => $now];
$lot['open'][$ticket['id']] = $ticket;
return $ticket;
}
function findFreeSpot(array $spots, int $size): ?int
{
$best = null;
foreach ($spots as $i => $spot) {
if ($spot['taken'] || $spot['size'] < $size) {
continue;
}
if ($best === null || $spot['size'] < $spots[$best]['size']) {
$best = $i;
}
}
return $best;
}
function exitLot(array &$lot, string $ticketId, int $now): int
{
$ticket = $lot['open'][$ticketId] ?? throw new RuntimeException('unknown ticket');
releaseSpot($lot['spots'], $ticket['spot_id']);
unset($lot['open'][$ticketId]);
return fee($ticket['entered_at'], $now);
}
function releaseSpot(array &$spots, int $spotId): void
{
foreach ($spots as &$spot) {
if ($spot['id'] === $spotId) {
$spot['taken'] = false;
return;
}
}
}
function fee(int $enteredAt, int $leftAt): int
{
return (intdiv($leftAt - $enteredAt, 3600) + 1) * 200;
}<?php
// Where plain functions win: a data pipeline. Collections give you map/filter/reduce without classes.
namespace App\Reports;
use Illuminate\Support\Collection;
/** @param iterable<string> $lines "alice,1250" */
function topSpenders(iterable $lines, int $n): Collection
{
return collect($lines)
->map(fn (string $line) => explode(',', $line, 2))
->filter(fn (array $p) => count($p) === 2 && is_numeric($p[1]))
->groupBy(fn (array $p) => trim($p[0]))
->map(fn (Collection $rows) => $rows->sum(fn (array $p) => (int) $p[1]))
->sortDesc()
->take($n);
}Relationships, contracts, methods and invariants:
<?php
// The six UML relationships in PHP 8.4.
namespace App\Relationships;
// Realization: a class implements an interface.
interface Notifier
{
public function notify(string $to, string $text): void;
}
final class EmailNotifier implements Notifier
{
public function notify(string $to, string $text): void {}
}
// Dependency: used only inside one method, never stored.
final class Report
{
public function __construct(private readonly string $title) {}
public function render(\Closure $write): void
{
$write("# {$this->title}\n");
}
}
// Association: an Order knows its Customer; both live on their own.
final readonly class Customer
{
public function __construct(public string $id, public string $name) {}
}
// Aggregation: a Team has Persons that are created elsewhere and outlive it.
final class Person
{
public function __construct(public readonly string $name) {}
}
final class Team
{
/** @var list<Person> */
private array $members = [];
public function add(Person $p): void
{
$this->members[] = $p;
}
}
// Composition: the Order creates and owns its lines; they die with it.
final readonly class Line
{
public function __construct(public string $sku, public int $qty, public int $cents) {}
}
final class Order
{
/** @var list<Line> */
private array $lines = [];
public function __construct(private readonly Customer $customer) {}
public function addLine(string $sku, int $qty, int $cents): void
{
$this->lines[] = new Line($sku, $qty, $cents);
}
/** @return list<Line> a copy; Line is immutable, so the composed parts stay protected */
public function lines(): array
{
return $this->lines;
}
}
// Inheritance: real in PHP, and virtual (unlike Go embedding). Use it for "is a", keep it shallow.
abstract class Shape
{
abstract public function area(): float;
public function describe(): string
{
return static::class.' with area '.$this->area(); // dispatches to the subclass
}
}
final class Circle extends Shape
{
public function __construct(private readonly float $r) {}
public function area(): float
{
return M_PI * $this->r ** 2;
}
}<?php
// PHP: a small interface owned by the consumer + final classes that implement it.
namespace App\Contracts;
use RuntimeException;
final readonly class User
{
public function __construct(public string $id, public string $name) {}
}
// One method, only what Greeter needs.
interface UserFinder
{
public function find(string $id): User;
}
// final: nobody can extend it and break its invariants; replace it by implementing the interface.
final class InMemoryUsers implements UserFinder
{
/** @param array<string, User> $rows */
public function __construct(private array $rows = []) {}
public function find(string $id): User
{
return $this->rows[$id] ?? throw new RuntimeException("user {$id} not found");
}
}
final readonly class Greeter
{
public function __construct(private UserFinder $users) {}
public function greet(string $id): string
{
return 'Hello, '.$this->users->find($id)->name;
}
}
// Laravel wiring (AppServiceProvider::register): bind the interface once, in one place.
// $this->app->bind(UserFinder::class, EloquentUsers::class);<?php
// Method design: command-query separation, a parameter object, honest return types.
namespace App\Methods;
use DateTimeImmutable;
use InvalidArgumentException;
final class Stack
{
/** @var list<mixed> */
private array $items = [];
// Command: changes state, returns nothing.
public function push(mixed $v): void
{
$this->items[] = $v;
}
// Query: changes nothing; null means empty.
public function peek(): mixed
{
return $this->items[array_key_last($this->items)] ?? null;
}
public function drop(): void
{
array_pop($this->items);
}
}
// Parameter object: named, validated, immutable.
final readonly class SearchParams
{
public function __construct(
public string $query,
public int $limit = 20,
public ?DateTimeImmutable $from = null,
public ?DateTimeImmutable $to = null,
public ?string $cursor = null,
) {
if ($query === '' || $limit < 1 || $limit > 100) {
throw new InvalidArgumentException('bad search params');
}
if ($from && $to && $to < $from) {
throw new InvalidArgumentException('to is before from');
}
}
}
final class SearchService
{
/** @return list<array{id: string, title: string}> */
public function search(SearchParams $p): array
{
return [['id' => '1', 'title' => $p->query]];
}
}
// Call site: named arguments make the intent readable.
// $hits = $service->search(new SearchParams(query: 'lld', limit: 10));<?php
// Constructors that enforce invariants; validation at the boundary, trust inside.
namespace App\Domain;
use InvalidArgumentException;
final readonly class Email
{
public string $value;
public function __construct(string $raw)
{
$v = strtolower(trim($raw));
filter_var($v, FILTER_VALIDATE_EMAIL) !== false || throw new InvalidArgumentException("invalid email: {$raw}");
$this->value = $v;
}
}
final readonly class Money
{
public function __construct(public int $cents, public string $currency)
{
$cents >= 0 || throw new InvalidArgumentException('money cannot be negative');
strlen($currency) === 3 || throw new InvalidArgumentException('currency must be 3 letters');
}
public function add(self $other): self
{
$this->currency === $other->currency || throw new InvalidArgumentException('currency mismatch');
return new self($this->cents + $other->cents, $this->currency);
}
}
// Boundary: a Form Request validates untrusted input; the domain constructor re-checks what it needs.
// app/Http/Requests/RegisterRequest.php
// public function rules(): array { return ['email' => ['required', 'email:rfc'], 'age' => ['required', 'integer', 'min:18']]; }
//
// Controller: new Email($request->validated('email')) // inside the app an Email is always validTestability and the anti-corruption layer:
<?php
// Time as a dependency. Production binds the system clock; tests bind a fixed one
// or use Laravel's own time helpers.
namespace App\Support;
use DateTimeImmutable;
use Illuminate\Support\Carbon;
use Illuminate\Support\ServiceProvider;
interface Clock
{
public function now(): DateTimeImmutable;
}
final class SystemClock implements Clock
{
public function now(): DateTimeImmutable
{
return new DateTimeImmutable;
}
}
final readonly class FrozenClock implements Clock
{
public function __construct(private DateTimeImmutable $at) {}
public function now(): DateTimeImmutable
{
return $this->at;
}
}
final class Session
{
private readonly DateTimeImmutable $started;
public function __construct(private readonly Clock $clock, private readonly int $ttlSeconds)
{
$this->started = $clock->now();
}
public function expired(): bool
{
return $this->clock->now()->getTimestamp() >= $this->started->getTimestamp() + $this->ttlSeconds;
}
}
final class ClockServiceProvider extends ServiceProvider
{
public function register(): void
{
$this->app->bind(Clock::class, SystemClock::class);
}
}
// Option 2 in a Laravel app: the framework's clock is already a seam.
// Production: Carbon::now() / now()
// Test: $this->travelTo(now()->addMinutes(31)); // or $this->freezeTime();
// Randomness: inject a Closure (fn (int $n): int => random_int(0, $n - 1)); tests pass fn () => 2.<?php
// Anti-corruption layer inside one service: the provider's shape stays in this file.
namespace App\Payments;
use RuntimeException;
enum Status: string
{
case Pending = 'pending';
case Paid = 'paid';
case Declined = 'declined';
case Review = 'needs_review';
}
final readonly class Payment
{
public function __construct(public string $id, public int $cents, public string $currency, public Status $status) {}
}
// What the rest of the service depends on.
interface PaymentGateway
{
public function charge(string $customerId, int $cents, string $currency): Payment;
}
// Translator: the only code that knows the provider spells amounts as "12.50" and statuses as 0..3.
final class ProviderTranslator
{
/** @param array{charge_id: string, amount: string, ccy: string, status: int} $raw */
public function toPayment(array $raw): Payment
{
$status = match ($raw['status']) {
0 => Status::Pending,
1 => Status::Paid,
2 => Status::Declined,
3 => Status::Review,
default => throw new RuntimeException("unknown provider status {$raw['status']}"),
};
return new Payment($raw['charge_id'], (int) round(((float) $raw['amount']) * 100), $raw['ccy'], $status);
}
}
final readonly class ProviderGateway implements PaymentGateway
{
/** @param \Closure(string, string, string): array $call raw provider call, e.g. an Http::post wrapper */
public function __construct(private \Closure $call, private ProviderTranslator $translator) {}
public function charge(string $customerId, int $cents, string $currency): Payment
{
$amount = sprintf('%d.%02d', intdiv($cents, 100), $cents % 100);
return $this->translator->toPayment(($this->call)($customerId, $amount, $currency));
}
}The Laravel angle
- Slots are LLD decisions made for you. A Form Request (interfacer and boundary validation), an Action or Job (controller), a Policy (rule), a Notification (message plus channel list), an API Resource (DTO for the response). Use them as the "class" level of your design and keep rules in plain classes behind them.
- Value objects and enums. PHP 8.4
final readonly classandenummake invariants cheap (Money,Email,Size). Eloquent casts ('status' => Status::class) keep enums in models. - Contracts and the container. Bind an interface to an implementation in a service provider:
$this->app->bind(Clock::class, SystemClock::class). Constructor type-hints are resolved by the container, so constructor injection needs no extra code (Laravel 13 container docs). - Time in tests.
$this->travelTo(...)and$this->freezeTime()(Laravel testing docs) fakenow()for the whole framework; aClockinterface is still the cleaner design for domain classes that should run without Laravel. - Notifications. A notification class declares channels in
via(object $notifiable): arrayand onetoMail,toDatabase, ... method per channel; addimplements ShouldQueueto queue delivery. UseNotification::send($users, new InvoicePaid($invoice))or$user->notify(...). This is the "channel list" half of the notification problem solved by the framework; you design the rest (preferences, limits, fallback) around it. - Rate limiting.
RateLimiter::attempt,tooManyAttempts,hit,remaining,availableInandclearstore counters in the cache; with the Redis cache driver they are shared across servers. - Eloquent is an Active Record. A model combines data, persistence and rules in one class; that is convenient and the opposite of the separation described here. For a rule-heavy domain keep a plain class and map to the model at the edge (Data Persistence in Design).
- Tooling. Larastan or PHPStan for types, Pest or PHPUnit for tests,
php artisan make:*generators for slots, Deptrac to enforce which namespace may call which.
Solving the classic problems
Worked problem 1: a parking lot Must-know
1. Clarify. Requirements we agree on: a single lot with spots of three sizes; a vehicle takes the smallest free spot that fits; entering returns a ticket; leaving takes the ticket and returns the fee; fee is per started hour, with a rate per vehicle size; the lot may be used from several goroutines or requests at once. Out of scope: payment collection, floors, reservations (we show where they plug in).
2. Entities. Nouns: lot, spot, ticket, vehicle size, fee, time. Keep Lot (state and rules), Spot (a private detail of the lot), Ticket (record), Size (closed set), FeePolicy (varies), Clock (time seam). Drop "vehicle" and "driver": we only need the size.
3. Relationships.
Lot composes Spots (they exist only inside it) and keeps open Tickets; FeePolicy and Clock are association to interface; HourlyFee and SystemClock realize them; Ticket and Spot use the Size enum.
4. APIs and contracts.
| Method | Contract | Errors |
|---|---|---|
NewLot(capacity, fees, clock) | At least one spot, known sizes, non-nil collaborators | error describing the violation |
Enter(size) (Ticket, error) | Gives the smallest free spot that fits; one ticket per call | ErrFull |
Exit(id) (Money, error) | Frees the spot, returns the fee for started hours | ErrUnknownTicket (also for a second exit) |
Free(size) int | Query; never changes state | none |
5. Walk a scenario. Done in Walking a scenario. 6. Extend. Weekend pricing is a new FeePolicy. EV spots add a new Size or a Feature filter in Enter. Multiple floors: a Garage that owns several Lots and picks one (composition again). Payment: a Payments interface called by Exit, or by a controller above the lot.
The complete Go solution (the code compiles and has tests; run it in the lab):
// Package parking is the object-oriented solution of the parking-lot LLD problem.
// Each type has one job: Lot coordinates, Spot holds state, Ticket is a record,
// FeePolicy is a service provider chosen at construction time.
package parking
import (
"errors"
"fmt"
"sync"
"time"
)
// Size orders vehicle and spot sizes; a vehicle fits any spot of its size or larger.
type Size int
const (
Small Size = iota + 1
Medium
Large
)
var (
ErrFull = errors.New("parking: lot is full")
ErrUnknownTicket = errors.New("parking: unknown ticket")
)
// Clock and FeePolicy are defined here, by the consumer, and kept to one method each.
type Clock interface{ Now() time.Time }
type FeePolicy interface {
Fee(size Size, stay time.Duration) Money
}
// HourlyFee charges per started hour, with a rate per vehicle size.
type HourlyFee struct{ PerHour map[Size]Money }
func (h HourlyFee) Fee(size Size, stay time.Duration) Money {
hours := int64(stay/time.Hour) + 1
return Money(hours) * h.PerHour[size]
}
type TicketID string
// Ticket is an immutable record handed to the driver.
type Ticket struct {
ID TicketID
SpotNo int
Size Size
EnteredAt time.Time
}
type spot struct {
no int
size Size
}
// entry remembers which spot a ticket occupies, so Exit can give the spot back to
// the right stack even when a small vehicle sat in a larger spot.
type entry struct {
ticket Ticket
spot spot
}
// Lot owns its spots (composition) and its open tickets. free keeps one stack of
// free spots per size, so Enter is O(sizes) and Exit is O(1); open is a map so a
// ticket lookup is O(1) instead of a scan.
type Lot struct {
mu sync.Mutex
fees FeePolicy
clock Clock
free map[Size][]spot
open map[TicketID]entry
nextID int
}
// NewLot enforces the invariants: at least one spot, known sizes, collaborators present.
func NewLot(capacity map[Size]int, fees FeePolicy, clock Clock) (*Lot, error) {
if fees == nil || clock == nil {
return nil, errors.New("parking: fees and clock are required")
}
l := &Lot{fees: fees, clock: clock, free: map[Size][]spot{}, open: map[TicketID]entry{}}
no := 0
for size, n := range capacity {
if size < Small || size > Large || n < 0 {
return nil, fmt.Errorf("parking: bad capacity %d for size %d", n, size)
}
for i := 0; i < n; i++ {
no++
l.free[size] = append(l.free[size], spot{no: no, size: size})
}
}
if no == 0 {
return nil, errors.New("parking: a lot needs at least one spot")
}
return l, nil
}
// Enter is a command that also returns the ticket: the one accepted exception to
// command-query separation, because issuing and returning must be one atomic step.
func (l *Lot) Enter(size Size) (Ticket, error) {
l.mu.Lock()
defer l.mu.Unlock()
for s := size; s <= Large; s++ {
stack := l.free[s]
if len(stack) == 0 {
continue
}
sp := stack[len(stack)-1]
l.free[s] = stack[:len(stack)-1]
l.nextID++
t := Ticket{ID: TicketID(fmt.Sprintf("T%d", l.nextID)), SpotNo: sp.no, Size: size, EnteredAt: l.clock.Now()}
l.open[t.ID] = entry{ticket: t, spot: sp}
return t, nil
}
return Ticket{}, ErrFull
}
// Exit releases the spot and returns the fee.
func (l *Lot) Exit(id TicketID) (Money, error) {
l.mu.Lock()
defer l.mu.Unlock()
e, ok := l.open[id]
if !ok {
return 0, ErrUnknownTicket
}
delete(l.open, id)
l.free[e.spot.size] = append(l.free[e.spot.size], e.spot)
return l.fees.Fee(e.ticket.Size, l.clock.Now().Sub(e.ticket.EnteredAt)), nil
}
// Free is a query: it never changes state.
func (l *Lot) Free(size Size) int {
l.mu.Lock()
defer l.mu.Unlock()
return len(l.free[size])
}package parking
import "fmt"
// Money is an amount in minor units (cents). A named type keeps cents and
// plain integers from being mixed by accident.
type Money int64
func (m Money) String() string {
return fmt.Sprintf("%d.%02d", int64(m)/100, int64(m)%100)
}The test uses a fakeClock; no time.Sleep, no real time:
package parking
import (
"testing"
"time"
)
// fakeClock is the seam: the Lot never calls time.Now itself.
type fakeClock struct{ now time.Time }
func (c *fakeClock) Now() time.Time { return c.now }
func newTestLot(t *testing.T, clock Clock) *Lot {
t.Helper()
fees := HourlyFee{PerHour: map[Size]Money{Small: 100, Medium: 200, Large: 400}}
lot, err := NewLot(map[Size]int{Small: 1, Medium: 1}, fees, clock)
if err != nil {
t.Fatal(err)
}
return lot
}
func TestEnterExitCharges(t *testing.T) {
clock := &fakeClock{now: time.Date(2026, 1, 1, 9, 0, 0, 0, time.UTC)}
lot := newTestLot(t, clock)
tk, err := lot.Enter(Small)
if err != nil {
t.Fatal(err)
}
clock.now = clock.now.Add(90 * time.Minute)
got, err := lot.Exit(tk.ID)
if err != nil {
t.Fatal(err)
}
if got != 200 { // 1h30 -> 2 started hours x 100
t.Fatalf("fee = %v, want 2.00", got)
}
}
func TestSmallCarTakesBiggerSpotWhenSmallIsFull(t *testing.T) {
lot := newTestLot(t, &fakeClock{now: time.Unix(0, 0)})
if _, err := lot.Enter(Small); err != nil {
t.Fatal(err)
}
if _, err := lot.Enter(Small); err != nil { // falls through to the medium spot
t.Fatal(err)
}
if _, err := lot.Enter(Small); err != ErrFull {
t.Fatalf("err = %v, want ErrFull", err)
}
if lot.Free(Small)+lot.Free(Medium) != 0 {
t.Fatal("lot should be full")
}
}
func TestExitReturnsSpotToItsOwnSize(t *testing.T) {
lot := newTestLot(t, &fakeClock{now: time.Unix(0, 0)})
lot.Enter(Small)
tk, _ := lot.Enter(Small) // sits in the medium spot
if _, err := lot.Exit(tk.ID); err != nil {
t.Fatal(err)
}
if lot.Free(Medium) != 1 {
t.Fatalf("medium free = %d, want 1", lot.Free(Medium))
}
if _, err := lot.Exit(tk.ID); err != ErrUnknownTicket {
t.Fatalf("second exit err = %v, want ErrUnknownTicket", err)
}
}
func TestNewLotRejectsEmptyLot(t *testing.T) {
if _, err := NewLot(map[Size]int{}, HourlyFee{}, &fakeClock{}); err == nil {
t.Fatal("expected an error for a lot without spots")
}
}The Laravel/PHP version of the same design:
<?php
// Object-oriented parking lot (worked problem 1). Same responsibilities as the Go version.
namespace App\Parking;
use DateInterval;
use DateTimeImmutable;
use InvalidArgumentException;
use RuntimeException;
enum Size: int
{
case Small = 1;
case Medium = 2;
case Large = 3;
}
// Small contracts, owned by the consumer (the lot).
interface Clock
{
public function now(): DateTimeImmutable;
}
interface FeePolicy
{
/** Fee in minor units (cents). */
public function fee(Size $size, DateInterval $stay): int;
}
final readonly class Ticket
{
public function __construct(
public string $id,
public int $spotNo,
public Size $size,
public DateTimeImmutable $enteredAt,
) {}
}
final readonly class HourlyFee implements FeePolicy
{
/** @param array<int, int> $perHour cents per started hour, keyed by Size value */
public function __construct(private array $perHour) {}
public function fee(Size $size, DateInterval $stay): int
{
$hours = $stay->days * 24 + $stay->h + 1; // every started hour counts
return $hours * $this->perHour[$size->value];
}
}
final class ParkingLot
{
/** @var array<int, list<array{no: int, size: Size}>> free spots, one stack per size value */
private array $free = [1 => [], 2 => [], 3 => []];
/** @var array<string, array{ticket: Ticket, spot: array{no: int, size: Size}}> */
private array $open = [];
private int $nextId = 0;
/** @param array<int, int> $capacity spots per Size value */
public function __construct(array $capacity, private readonly FeePolicy $fees, private readonly Clock $clock)
{
$no = 0;
foreach ($capacity as $sizeValue => $count) {
$size = Size::tryFrom($sizeValue) ?? throw new InvalidArgumentException("bad size {$sizeValue}");
for ($i = 0; $i < $count; $i++) {
$this->free[$sizeValue][] = ['no' => ++$no, 'size' => $size];
}
}
$no > 0 || throw new InvalidArgumentException('a lot needs at least one spot');
}
public function enter(Size $size): Ticket
{
for ($s = $size->value; $s <= Size::Large->value; $s++) {
$spot = array_pop($this->free[$s]);
if ($spot === null) {
continue;
}
$ticket = new Ticket('T'.(++$this->nextId), $spot['no'], $size, $this->clock->now());
$this->open[$ticket->id] = ['ticket' => $ticket, 'spot' => $spot];
return $ticket;
}
throw new RuntimeException('lot is full');
}
public function exit(string $ticketId): int
{
$entry = $this->open[$ticketId] ?? throw new RuntimeException('unknown ticket');
unset($this->open[$ticketId]);
$this->free[$entry['spot']['size']->value][] = $entry['spot'];
$stay = $entry['ticket']->enteredAt->diff($this->clock->now());
return $this->fees->fee($entry['ticket']->size, $stay);
}
public function free(Size $size): int
{
return count($this->free[$size->value]);
}
}Persistence. In a monolith with a database the same rules are mirrored as constraints, so two requests cannot take the same spot even without the in-memory mutex:
-- PostgreSQL: the schema repeats the invariants of the class.
CREATE TABLE spots (
id serial PRIMARY KEY,
size smallint NOT NULL CHECK (size BETWEEN 1 AND 3)
);
CREATE TABLE tickets (
id bigserial PRIMARY KEY,
spot_id int NOT NULL REFERENCES spots(id),
size smallint NOT NULL CHECK (size BETWEEN 1 AND 3),
entered_at timestamptz NOT NULL,
left_at timestamptz,
CHECK (left_at IS NULL OR left_at >= entered_at)
);
-- At most one open ticket per spot, enforced by the database.
CREATE UNIQUE INDEX one_open_ticket_per_spot ON tickets (spot_id) WHERE left_at IS NULL;
-- Allocate the smallest free spot that fits, without two requests picking the same row.
SELECT s.id FROM spots s
WHERE s.size >= 1
AND NOT EXISTS (SELECT 1 FROM tickets t WHERE t.spot_id = s.id AND t.left_at IS NULL)
ORDER BY s.size, s.id
LIMIT 1
FOR UPDATE OF s SKIP LOCKED;| Solution | How | Advantage | Cost or limit |
|---|---|---|---|
One mutex in the Lot | sync.Mutex around Enter and Exit | Simple, correct for one process | One process only; contention at high rates |
| Unique partial index | Database rejects a second open ticket per spot | Correct across processes | Needs a retry on conflict |
FOR UPDATE SKIP LOCKED | Workers skip rows locked by others | No waiting, no deadlock between workers | Query shape must stay as above |
| Per-floor lots | Shard by floor | Less contention | More objects, routing logic |
Worked problem 2: a notification system Must-know
1. Clarify. Send a notification to a user by email, SMS or push; the user can switch channels off per kind (security, billing, marketing); try channels in preference order and fall back if one fails; limit non-security notifications to a burst of 5 then 1 per second per user; security notices are never limited. Out of scope: templates, scheduling, retries with backoff, delivery receipts (see retry and backoff and the outbox for how they plug in).
2. Entities. Notification (what), Recipient (who), Channel (how; varies), Preferences (may I), RateLimiter (how often), Dispatcher (the coordinator), Clock (time seam). Drop User (we only need an id and addresses) and Template.
3. Relationships.
Dispatcher holds an ordered list of Channels (association to an interface, one to many), a Preferences and a RateLimiter; RateLimiter holds a Clock; the three channels realize Channel; Notification and Recipient are data the dispatcher uses.
4. APIs and contracts.
| Method | Contract | Errors |
|---|---|---|
NewDispatcher(prefs, limiter, channels...) | Non-nil collaborators, at least one channel | construction error |
Dispatcher.Send(ctx, to, n) (string, error) | Returns the name of the channel that delivered; tries allowed channels in order; non-security obey the limiter | ErrRateLimited, ErrNoChannel joined with each channel failure |
Channel.Send(ctx, to, n) error | Deliver or fail; must respect ctx | any error |
Preferences.Allows(user, kind, channel) bool | Query; no side effects | none |
RateLimiter.Allow(key) bool | Takes one token if available | none |
Step Scenario: prefs allow push+email; push is offline; limiter burst 5
1 1 Send(u1, Billing) -> limiter.Allow(u1) = true (token 5 -> 4)
2 2 push: prefs allow -> Send fails "device offline" -> failure recorded
3 3 email: prefs allow -> Send ok -> return "email"
4 4 Send(u1, Security) -> limiter skipped -> push offline -> email -> "email"
5 5 Send(u1, Marketing) x6 -> 5 pass, the 6th returns ErrRateLimited
6 6 all channels off for Marketing -> ErrNoChannel (no failures, nothing tried)5. Extend. A new channel (Slack, WhatsApp) is a new type implementing Channel, added to the list; the Dispatcher is unchanged. A per-kind policy ("security tries all channels at once") becomes a Strategy the dispatcher is constructed with. Retries with delay and persistence become a queue between Send and the channels (see Messaging).
The Go solution (compiles, has tests):
// Package notify is the second worked LLD problem: a notification system with
// several channels, per-user preferences, a per-user rate limit and fallback.
package notify
import (
"context"
"errors"
"fmt"
"time"
)
// Kind classifies a notification so preferences can be set per kind.
type Kind string
const (
Security Kind = "security"
Marketing Kind = "marketing"
Billing Kind = "billing"
)
// Notification is the value being delivered; Recipient is who gets it.
type Notification struct {
Kind Kind
Subject string
Body string
}
type Recipient struct {
UserID string
Email string
Phone string
}
// Channel is the consumer-side contract each delivery mechanism realizes.
type Channel interface {
Name() string
Send(ctx context.Context, to Recipient, n Notification) error
}
// Preferences answers one question, so a database, a cache or a map can back it.
type Preferences interface {
Allows(userID string, kind Kind, channel string) bool
}
type Clock interface{ Now() time.Time }
// RateLimiter is a token bucket per user, driven by the injected Clock.
type RateLimiter struct {
clock Clock
burst float64
perSec float64
buckets map[string]*bucket
}
type bucket struct {
tokens float64
last time.Time
}
func NewRateLimiter(c Clock, perSec float64, burst int) *RateLimiter {
return &RateLimiter{clock: c, perSec: perSec, burst: float64(burst), buckets: map[string]*bucket{}}
}
// Allow takes one token for key if available. Map lookup keeps it O(1) per call.
func (r *RateLimiter) Allow(key string) bool {
now := r.clock.Now()
b, ok := r.buckets[key]
if !ok {
b = &bucket{tokens: r.burst, last: now}
r.buckets[key] = b
}
b.tokens = min(r.burst, b.tokens+now.Sub(b.last).Seconds()*r.perSec)
b.last = now
if b.tokens < 1 {
return false
}
b.tokens--
return true
}
var (
ErrRateLimited = errors.New("notify: rate limited")
ErrNoChannel = errors.New("notify: no channel accepted the notification")
)
// Dispatcher is the coordinator: it decides who is asked, in which order,
// and what happens on failure. It does no delivery work itself.
type Dispatcher struct {
channels []Channel // preference order, e.g. push, email, sms
prefs Preferences
limiter *RateLimiter
}
func NewDispatcher(prefs Preferences, limiter *RateLimiter, channels ...Channel) (*Dispatcher, error) {
if prefs == nil || limiter == nil || len(channels) == 0 {
return nil, errors.New("notify: preferences, limiter and at least one channel are required")
}
return &Dispatcher{channels: channels, prefs: prefs, limiter: limiter}, nil
}
// Send tries each allowed channel in order and stops at the first success.
// Security notifications skip the rate limit; everything else obeys it.
func (d *Dispatcher) Send(ctx context.Context, to Recipient, n Notification) (string, error) {
if n.Kind != Security && !d.limiter.Allow(to.UserID) {
return "", ErrRateLimited
}
var failures []error
for _, ch := range d.channels {
if !d.prefs.Allows(to.UserID, n.Kind, ch.Name()) {
continue
}
if err := ch.Send(ctx, to, n); err != nil {
failures = append(failures, fmt.Errorf("%s: %w", ch.Name(), err))
continue
}
return ch.Name(), nil
}
return "", errors.Join(append([]error{ErrNoChannel}, failures...)...)
}package notify
import (
"context"
"errors"
"testing"
"time"
)
type fakeClock struct{ now time.Time }
func (f *fakeClock) Now() time.Time { return f.now }
type fakeChannel struct {
name string
err error
sent int
}
func (f *fakeChannel) Name() string { return f.name }
func (f *fakeChannel) Send(context.Context, Recipient, Notification) error {
if f.err != nil {
return f.err
}
f.sent++
return nil
}
type allowAll struct{}
func (allowAll) Allows(string, Kind, string) bool { return true }
func TestFallsBackToNextChannel(t *testing.T) {
push := &fakeChannel{name: "push", err: errors.New("device offline")}
email := &fakeChannel{name: "email"}
lim := NewRateLimiter(&fakeClock{now: time.Unix(0, 0)}, 1, 5)
d, err := NewDispatcher(allowAll{}, lim, push, email)
if err != nil {
t.Fatal(err)
}
via, err := d.Send(context.Background(), Recipient{UserID: "u1"}, Notification{Kind: Billing})
if err != nil || via != "email" {
t.Fatalf("via=%q err=%v", via, err)
}
}
func TestRateLimitSkipsSecurity(t *testing.T) {
ch := &fakeChannel{name: "email"}
clock := &fakeClock{now: time.Unix(0, 0)}
d, _ := NewDispatcher(allowAll{}, NewRateLimiter(clock, 0.001, 1), ch)
ctx := context.Background()
to := Recipient{UserID: "u1"}
if _, err := d.Send(ctx, to, Notification{Kind: Marketing}); err != nil {
t.Fatal(err)
}
if _, err := d.Send(ctx, to, Notification{Kind: Marketing}); !errors.Is(err, ErrRateLimited) {
t.Fatalf("second marketing send: err=%v, want ErrRateLimited", err)
}
if _, err := d.Send(ctx, to, Notification{Kind: Security}); err != nil {
t.Fatalf("security must bypass the limiter: %v", err)
}
}
func TestBucketRefillsWithTime(t *testing.T) {
clock := &fakeClock{now: time.Unix(0, 0)}
lim := NewRateLimiter(clock, 1, 1)
if !lim.Allow("k") || lim.Allow("k") {
t.Fatal("burst of 1: first call allowed, second denied")
}
clock.now = clock.now.Add(time.Second)
if !lim.Allow("k") {
t.Fatal("one token should have refilled after a second")
}
}And the PHP/Laravel version, with the built-in Notification class for one channel list:
<?php
// Worked problem 2 in PHP: a notification system, plus the Laravel built-in way.
namespace App\Notify;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Facades\RateLimiter;
use RuntimeException;
enum Kind: string
{
case Security = 'security';
case Marketing = 'marketing';
case Billing = 'billing';
}
final readonly class Message
{
public function __construct(public Kind $kind, public string $subject, public string $body) {}
}
final readonly class Recipient
{
public function __construct(public string $userId, public ?string $email = null, public ?string $phone = null) {}
}
interface Channel
{
public function name(): string;
/** @throws RuntimeException when delivery fails */
public function send(Recipient $to, Message $m): void;
}
interface Preferences
{
public function allows(string $userId, Kind $kind, string $channel): bool;
}
final class RateLimited extends RuntimeException {}
// Coordinator: decides who is asked and in which order. It delivers nothing itself.
final class Dispatcher
{
/** @param list<Channel> $channels in preference order */
public function __construct(private readonly array $channels, private readonly Preferences $prefs)
{
$channels !== [] || throw new \InvalidArgumentException('at least one channel is required');
}
/** @return string the channel that delivered */
public function send(Recipient $to, Message $m): string
{
$key = "notify:{$to->userId}";
if ($m->kind !== Kind::Security && RateLimiter::tooManyAttempts($key, 5)) {
throw new RateLimited("rate limited: {$to->userId}");
}
$m->kind === Kind::Security || RateLimiter::hit($key, 60);
$failures = [];
foreach ($this->channels as $channel) {
if (! $this->prefs->allows($to->userId, $m->kind, $channel->name())) {
continue;
}
try {
$channel->send($to, $m);
return $channel->name();
} catch (RuntimeException $e) {
$failures[] = $channel->name().': '.$e->getMessage();
}
}
throw new RuntimeException('no channel accepted the notification; '.implode('; ', $failures));
}
}
// The Laravel-native shape of one channel list: a Notification class with via() and toMail().
final class InvoicePaid extends Notification implements ShouldQueue
{
use Queueable;
public function __construct(public readonly int $invoiceId) {}
/** @return list<string> */
public function via(object $notifiable): array
{
return ['mail', 'database'];
}
public function toMail(object $notifiable): MailMessage
{
return (new MailMessage)->subject("Invoice #{$this->invoiceId} paid")->line('Thank you.');
}
}
// Usage: $user->notify(new InvoicePaid($invoice->id));| Alternative | When | Trade-off |
|---|---|---|
Dispatcher with explicit channel list (above) | Custom fallback, preferences, limits | You build and test the coordinator |
Laravel Notification with via() | Standard email, database, broadcast, Slack | Fallback and preference logic go in via() or a custom channel |
| Queue per channel | High volume, slow providers | Eventual delivery, ordering across channels is lost |
| One message per channel plus an outbox | Must not lose a notification | More moving parts, exactly the outbox cost |
Other classic problems
| Problem | Smell in the first draft | Responsibility-based fix |
|---|---|---|
Manager or Helper class that does everything | Many unrelated methods, many collaborators | Split by role: coordinator, service providers, holders |
switch on a type string in many places | Adding a variant edits several files | Interface per variant, choose once at construction |
Primitive obsession (string email, int cents everywhere) | Validation repeated, units mixed | Email, Money value objects with invariants |
| Anemic records plus a giant service | Rules far from the data | Move behaviour next to the data it guards (information expert) |
Hidden time.Now() / now() / new Mailer() | Slow, flaky tests | Inject Clock, Channel |
| Interface per class "for mocking" | Parallel hierarchy, no consumer | Create the interface where it is consumed, when needed |
| Deep inheritance to share code | Fragile base class | Composition; small interface plus helper |
| Public mutable fields | Invariants broken anywhere | Unexported fields, methods that guard |
Choosing: which structure for which problem
| Problem | Recommended structure | Extra technique | Reason |
|---|---|---|---|
| Transformation of data (parse, filter, aggregate) | Functions and slices or Collection | Table-driven tests | No state, no variants |
| Rule-heavy domain with variants (pricing, discounts) | Classes with an interface per variant | Construct the variant once, inject it | Variants change independently |
| Long-lived stateful object (lot, session, pool) | A type guarding its state | Constructor invariants, mutex | The rules need an owner |
| Integration with a foreign system | Gateway interface plus translator (ACL) | DTO at the boundary | Keeps foreign vocabulary out |
| Variation by configuration only | One type with a parameter | Validate at construction | A class per value is noise |
| Many channels or plug-ins, new ones monthly | Interface plus registry or list | Contract tests | Add by adding a type |
| One caller, one implementation, unlikely to change | Concrete type, no interface | Add the interface when the second need appears | Avoid speculative abstraction (YAGNI) |
| Throwaway script | One function | Nothing | Cost of structure exceeds the benefit |
| Heuristic | Say yes to a new class when | Say no when |
|---|---|---|
| Responsibility | It has a verb the others do not | It only forwards calls |
| Variation | Two variants exist today | One variant "might come" |
| State | It guards an invariant | It is a bag of getters |
| Testing | It removes a hard dependency from tests | It adds a mock-only interface |
In architecture: from a single process to a distributed system
LLD is the same question at every size: "who is responsible for this?" What changes is what a mistake costs and which parts can be changed independently.
Monolith: one process, one database
How it shows up: classes in namespaces or packages in one deployable. The failures are the god class, the fat controller and the Helpers file.
Everyday example: the parking Lot above in a single Go binary or a Laravel app: one in-memory Lot behind a mutex (or one row-locking query in Postgres), a FeePolicy chosen in the composition root, a Clock injected for tests.
Production example: Laravel's own notification system. $user->notify(new InvoicePaid($invoice)) resolves channels through via(), queues delivery when the class implements ShouldQueue, and sends through a channel class per medium; the design is exactly "coordinator plus a list of Channels". In Go, golang.org/x/time/rate's Limiter is a service provider with one job and an explicit Clock-like time argument in AllowN(t time.Time, n int).
Modular monolith and multiple databases
How it shows up: each module (parking, billing, notifications) has its own classes, tables and public facade. Other modules call the facade, never the classes inside.
Everyday example: Parking calls Billing.Charge(ticketID, amount) through an interface owned by Parking, implemented by Billing's facade. The FeePolicy is parking's; the invoice is billing's.
Production example: enforce the boundary with a tool: Deptrac for PHP namespaces, internal/ directories and go-arch-lint for Go packages, CODEOWNERS per path. Each module owns its schema (CREATE SCHEMA parking), as shown on SRP.
| Rule | Why |
|---|---|
| A module exposes a facade and DTOs, not entities | Entities carry invariants other modules should not touch |
| A module owns its tables; others read through the facade or an event | One writer per table |
| Cross-module calls are interfaces defined by the caller | The caller states what it needs (consumer-owned contracts) |
Microservices: LLD with a network boundary
What survives: everything on this page applies inside each service. What changes: relationships across services are no longer method calls. An "association" becomes a stored id, "composition" stops at the service boundary, "realization" becomes a published schema.
Everyday example: the notification service. Dispatcher and its channels live in one service; Preferences is backed by the user-settings service through a small client behind the Preferences interface; if that call fails, the dispatcher uses a cached answer or a safe default (design the fallback, see Distribution of Components).
Production example: a payment provider behind an anti-corruption layer. The service defines PaymentGateway in its own language; the ACL translates the provider's DTO (charge_id, string amounts, numeric status) to Payment; unknown statuses fail loudly. Microsoft's Azure Architecture Center describes the pattern: "Isolate the different subsystems by placing an anti-corruption layer between them."
Step A request across services, LLD view
1 1 client POST /parking/exit {ticket: T7}
2 2 parking: Lot.Exit(T7) -> fee 600 (domain model, local)
3 3 parking publishes ParkingExited{ticket: T7, cents: 600} (DTO, versioned)
4 4 billing consumes it -> toPayment translator -> Payment aggregate (billing's own model)
5 5 notifications consumes PaymentCaptured -> Dispatcher.Send(...)
6 6 each service maps the message to its own model; none imports another's classes| Concern | Rule |
|---|---|
| Shared classes between services | No. Share schemas (OpenAPI, protobuf), not code |
| DTO vs domain model | Separate types, mapped at the boundary |
| Foreign vocabulary | ACL per foreign system |
| Ids | Reference other services' entities by id, not by object |
| Failure of a collaborator | The contract says what the caller sees: error, cached value, default |
Distributed data: replicas, caches and multi-node state
Where LLD breaks: state kept in a class instance is per process. Two instances of the parking service each have their own Lot; both can hand out spot 4. A RateLimiter with an in-memory map allows N times the limit with N nodes. A cache in front of Preferences can serve a stale "marketing off" answer for a few minutes.
Everyday example: run two copies of the parking service. Replace the in-memory free stacks by the SQL above: the unique partial index makes the database the single arbiter, SKIP LOCKED keeps workers from queueing, and the Lot class keeps its API unchanged because the storage sits behind a repository interface.
Production example: Laravel's RateLimiter stores counters in the configured cache store, so with the Redis cache driver all web servers share one counter; a Go service can use a Redis-backed limiter or a gateway-level limit instead of a per-process x/time/rate limiter.
| Failure | Cause | LLD answer |
|---|---|---|
| Double allocation | Per-process state, two nodes | Move the invariant to the database (unique index, row lock) |
| Limit multiplied by node count | Per-process counters | Shared store (Redis) or edge limiter |
| Stale preferences | Cache without invalidation | Short TTL, versioned key, or accept and document |
| Duplicate notification | At-least-once delivery from the queue | Idempotent Send keyed by notification id (see Idempotent Consumers) |
| Clock skew between nodes | Different Now() per node | Take time from the database or one source for ordering decisions |
Scaling path: 1×, 10×, 100×
| Scale | Structure | LLD practice |
|---|---|---|
| 1× (one team, one app) | A few packages, concrete types, interfaces only at seams | One-page LLD, constructor injection, fake clock |
| 10× (several teams, modular monolith) | Modules with facades and consumer-owned interfaces | Architecture tests, DTOs between modules, unique indexes for invariants |
| 100× (many services, many deploys) | Service-local models, ACLs, published schemas | Contract tests, idempotent handlers, per-service LLD docs and ADRs |
| Any | Reassess the LLD when a change touches more than one module | Move the responsibility, not the code around it |
Lab: build, break and extend the design
You run the snippets, change the pricing rule in both styles, and extend the notification system without touching its coordinator. Everything runs offline.
Setup.
cd docs/snippets/design/low-level-design/go
gofmt -l . # no output
go vet ./... # no output
go test ./... # ok for acl, contracts, invariants, notify, parking, testabilityStep 1: read the structured version. Open structured/parking.go. Draw the structure chart (modules and what each passes). Expected: IssueTicket -> findFreeSpot, Exit -> releaseSpot, fee.
Step 2: add weekend pricing, structured. Edit fee to take a weekend bool; update Exit. Count the files and functions you touched. Expected: 1 file, 2 functions, and every existing call site of fee changes.
Step 3: add weekend pricing, object-oriented. In parking/, add a type:
type WeekendFee struct{ Base FeePolicy }
func (w WeekendFee) Fee(size Size, stay time.Duration) Money { return w.Base.Fee(size, stay) * 2 }Construct a Lot with it. Expected: Lot is untouched, lot_test.go still passes, you add one test for WeekendFee.
Step 4: break an invariant. In invariants/, call NewMoney(-1, "EUR"). Expected: an error, no Money. Then try to write invariants.Money{} with a non-empty field from another package: the compiler rejects it (unexported fields).
Step 5: remove the seam. In testability/, replace s.clock.Now() with time.Now() and rerun the test. Expected: TestSessionExpires fails (the fake clock is ignored). Revert.
Step 6: extend the notifier. In notify/notify_test.go, add a channel by writing a new fakeChannel{name: "sms"} and appending it to the NewDispatcher arguments. Expected: no edit to notify.go.
Step 7: race check.
go test -race ./parking/Expected: pass. Now remove the l.mu.Lock() lines in Enter and write a test that calls Enter from 50 goroutines. Expected: -race reports a data race. Restore the lock.
Step 8 (PHP, optional). Read ParkingLot.php and Notifications.php. List the roles (information holder, service provider, coordinator) in each file.
| Metric | Structured | Object-oriented |
|---|---|---|
| Files touched to add weekend pricing | 1 (plus all callers of fee) | 1 new type, 0 edits to Lot |
| Test of the fee in isolation | needs a lot or a copy of fee | WeekendFee{...}.Fee(...) alone |
| Cost of finding a ticket | map lookup | map lookup |
| Where the "taken" flag is changed | IssueTicket, releaseSpot | only Lot |
Common misconceptions
| Belief | Reality |
|---|---|
| "LLD is UML" | LLD is decisions; UML is one way to draw them |
| "More classes means better design" | More classes means more to read; add one when it has a responsibility |
| "Every class needs an interface" | Interfaces belong where there is a consumer or a variant |
| "OO is always better than procedural" | Pipelines and transformations are clearer as functions |
| "Go has no OO design" | Go has types, methods, interfaces and composition; it lacks inheritance |
| "Composition and aggregation are the same" | Composition means the whole owns the parts' lifetime; aggregation does not |
| "Inheritance is how you reuse code" | Composition is the default; inheritance only for true is-a |
| "Getters and setters mean encapsulation" | Encapsulation is guarding invariants; a setter for every field exposes everything |
| "Validate in the controller and you are safe" | Validate at every boundary and in the constructor |
| "Mock every dependency" | Fake the seams (time, network, database); use real objects elsewhere |
| "Microservices need shared model libraries" | Share schemas, not classes |
| "The LLD interview wants patterns" | It wants requirements, responsibilities and an extensible design |
Cheat sheet
| Topic | What to remember |
|---|---|
| LLD vs HLD | HLD picks the boxes; LLD designs inside one box |
| Structured design | Call tree of procedures; structure chart; data couples; top-down |
| OO design | Responsibilities with owned data; class diagram; polymorphism for variants |
| Procedural wins | Pipelines, handlers, scripts, algorithms |
| Role stereotypes | Information holder, structurer, service provider, controller, coordinator, interfacer |
| GRASP first question | Information expert: give the job to whoever has the data |
| Ownership | Composition owns; aggregation shares; association knows; dependency uses |
| Interfaces | Small, consumer-owned; Go: accept interfaces, return structs; PHP: interface plus final class |
| Methods | Command or query; parameter object after three arguments; name the failures |
| Invariants | Constructor establishes, methods preserve, fields private, DB constraint last |
| Testability | Inject Clock and randomness; fake at seams, not everywhere |
| Data structures | Map for lookup by id; stack for latest free; state the cost |
| Interview method | Clarify, entities, relationships, APIs, scenario, extend, limits |
| Microservice LLD | Service-local model, DTO at boundary, ACL for foreign systems |
| Distributed state | Per-process state does not scale out; move invariants to the database |
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 is the difference between HLD and LLD, and what artifacts does each produce? Must-know
Answer
Answer: HLD chooses components, data stores and protocols (architecture diagram, capacity numbers). LLD designs inside one component: classes, responsibilities, relationships, method contracts, invariants (class and sequence diagrams, signatures).
2 — Name two pictures of structured design and what each shows. Good to know
Answer
Answer: The structure chart shows modules, who calls whom and the data passed on each call. The data-flow diagram shows processes, data stores, external entities and the flows between them, with no control flow.
3 — Why is "find the nouns" an incomplete way to find classes? Important
Answer
Answer: Nouns give candidates only. A class needs a responsibility (a verb). A noun without behaviour is a record; a responsibility without a noun (computing the fee) still needs a home.
4 — List the six Wirfs-Brock role stereotypes and give a parking example for three of them. Good to know
Answer
Answer: Information holder (Ticket), structurer (the lot's free stacks and open map), service provider (FeePolicy), controller (the "car arrives" use case), coordinator (Lot.Enter, Dispatcher), interfacer (HTTP handler, payment ACL).
5 — What is the difference between aggregation and composition, and how does Go express each? Important
Answer
Answer: Composition: the whole creates and owns the parts, and they die with it (lines []Line built inside Order, copies handed out). Aggregation: the whole refers to parts that live elsewhere (members []*Person passed in). UML 2.5.1 defines composite aggregation by exclusive ownership and deletion with the owner.
6 — Why does Go's "accept interfaces, return structs" put the interface in the consumer's package? Important
Answer
Answer: The consumer knows which methods it uses; the producer returning a concrete type can add methods freely without breaking anyone. The interface stays as small as the caller's need, which also makes a fake trivial.
7 — Is Pop() a violation of command-query separation? Should you remove it? Important
Answer
Answer: Yes, it changes state and returns a value. Meyer and Fowler accept it as an exception: remove-and-return must be one atomic step, especially with concurrency. Keep it, and provide Peek and Drop for the separated cases.
8 — How do you make "a session expires after 30 minutes" testable without waiting? Important
Answer
Answer: Inject a Clock (an interface with Now()), give the session the clock in its constructor, and use a fake clock in tests that you advance by 30 minutes. In Laravel feature tests, travelTo or freezeTime do the same for now().
9 — Why does the parking lot keep one stack of free spots per size plus a map of open tickets? Important
Answer
Answer: Enter needs the smallest free spot that fits in O(sizes), not a scan of all spots; Exit needs the ticket by id in O(1). The cost is that the lot must keep the structures consistent, which is why they are private.
10 — What breaks if you run two instances of the parking service with the in-memory Lot? Must-know
Answer
Answer: Each instance has its own free stacks, so both can issue spot 4. Move the invariant to the database (unique partial index on open tickets, FOR UPDATE SKIP LOCKED to allocate) and keep the Lot API behind a repository interface.
11 — What does an anti-corruption layer contain and why is it needed? Important
Answer
Answer: A gateway interface in the service's own language, a translator from the foreign DTO to the domain model, and failure on unknown values. It keeps another system's vocabulary (string amounts, numeric status codes) out of the domain and lets that system change in one file.
12 — In an LLD interview, what do you do before drawing any class? Must-know
Answer
Answer: Clarify: actors, scale, rules, constraints and out-of-scope items. Write the requirements as a numbered list and get agreement, then list entities.
Glossary
| Term | Meaning |
|---|---|
| Low-level design (LLD) | Design of classes, functions, relationships and contracts inside one component |
| High-level design (HLD) | Design of components, data stores and protocols between them |
| Detailed design | SWEBOK's name for the design stage that LLD covers |
| Structured design | Decomposition by procedure, with data and code separate (Yourdon and Constantine) |
| Structure chart | Tree of modules with the data passed on each call |
| Data-flow diagram (DFD) | Processes, stores, entities and data flows, without control flow |
| Top-down decomposition | Splitting a task into steps, then each step into smaller steps |
| Stepwise refinement | Wirth's name for top-down decomposition by successive detail |
| Data couple | A module passes simple data to another; the loosest coupling in the 1974 paper |
| Object-oriented design | Decomposition into objects that combine state and behaviour |
| Responsibility | Something an object knows, does, or decides |
| Collaborator | Another object a class asks for help |
| Responsibility-driven design | Wirfs-Brock and Wilkerson's method: design by contracts and responsibilities |
| CRC card | Class, Responsibility, Collaborators card (Beck and Cunningham, 1989) |
| Role stereotype | A recurring role: information holder, structurer, service provider, controller, coordinator, interfacer |
| Information holder | Role that knows and provides information |
| Structurer | Role that maintains relationships between objects |
| Service provider | Role that performs work and offers a service |
| Controller | Role that makes decisions and directs others |
| Coordinator | Role that reacts to events by delegating |
| Interfacer | Role that transforms information and requests between parts, or to another system |
| GRASP | Larman's nine principles for assigning responsibilities |
| Information expert | GRASP: give the job to the class that has the information |
| Creator | GRASP: who creates an object |
| Pure fabrication | GRASP: an invented class that has no domain counterpart |
| Indirection | GRASP: put a mediator between two things |
| Protected variations | GRASP: wrap an unstable point behind a stable interface |
| Dependency | Uses another class for one call and keeps nothing |
| Association | A class holds a long-lived reference to another |
| Aggregation | Whole-part with shared lifetime semantics; parts outlive the whole |
| Composition | Whole-part where the whole owns the parts and they die with it |
| Inheritance | Subtype relationship (is-a); not available in Go |
| Realization | A type implements an interface or contract |
| Embedding | Go's reuse mechanism: a struct field promotes the embedded type's methods; not subtyping |
| Contract | The preconditions, postconditions and failures of a method or interface |
| Accept interfaces, return structs | Go idiom: parameters are small interfaces, results are concrete types |
final class | PHP class that cannot be extended |
readonly class | PHP 8.2+ class whose properties are initialised once and immutable |
| Command-query separation (CQS) | A method either changes state or returns a result, not both (Meyer) |
| Parameter object | A type that groups arguments that travel together |
| Invariant | A condition that is always true about an object after any public call |
| Value object | An immutable object compared by value (Money, Email) |
| Boundary validation | Converting untrusted input into valid objects once, at the edge |
| Seam | A place where behaviour can be replaced without editing the code there |
| Dependency injection | Supplying collaborators from outside, usually through the constructor |
| Fake | A simple working substitute for a dependency (fake clock, in-memory store) |
| Token bucket | Rate-limiting structure: a bucket of tokens refilled at a fixed rate; one per request |
| Sentinel error | A package-level error value compared with errors.Is |
| Service-local model | The domain classes inside one service, never shared as a library |
| DTO (Data Transfer Object) | A flat structure for crossing a boundary |
| Anti-corruption layer (ACL) | Gateway plus translator that shields a model from a foreign one |
| Facade | One narrow entry point to a module |
| God class | A class with many roles and many reasons to change |
| Anemic model | Classes that hold data only, with rules in separate services |
| Primitive obsession | Using raw strings and integers where a domain type belongs |
References
- W. P. Stevens, G. J. Myers, L. L. Constantine, "Structured Design", IBM Systems Journal 13(2), 1974. PDF copy. Saved as
stevens-1974.txt. - Wikipedia, Structure chart, Structured analysis, Data-flow diagram (secondary sources for the structured-design tools and the Yourdon, Constantine and DeMarco history).
- Wikipedia, Responsibility-driven design and GRASP (secondary sources; the books by Wirfs-Brock and McKean, 2002, and Larman were not read).
- Martin Fowler, Command Query Separation, Tell Don't Ask, Value Object, Aggregation and Composition (the bliki entries as read in the sibling chapters), Introduce Parameter Object.
- OMG, Unified Modeling Language 2.5.1 (formal/2017-12-05), section 9.9 Property and
AggregationKind. omg.org/spec/UML/2.5.1 - SWEBOK Guide V4.0, IEEE Computer Society, October 2024, Chapter 3 Software Design, section 2.2 Detailed Design. PDF
- Gamma, Helm, Johnson, Vlissides, Design Patterns (1994), chapter 1, "Inheritance versus Composition".
- Go: Code Review Comments: Interfaces, Effective Go: Interfaces, Go Proverbs, Error handling and Go, Errors are values, package time, golang.org/x/time/rate.
- PHP manual: Final keyword, Constructor promotion, Properties and readonly.
- Laravel 13: Service container, Notifications, Mocking: time, Rate limiting.
- Microsoft Azure Architecture Center, Anti-corruption Layer pattern.
- Parnas 1972 and Beck and Cunningham 1989 are covered on SRP and The Design Process.