Skip to content

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 forGo to
The whole chapter in a few tablesEverything in one minute
What LLD is and why it existsWhy LLD exists
Yourdon, Constantine, Wirfs-Brock, Larman, MeyerWhere it comes from
LLD vs HLD, and where LLD sitsLLD and where it sits
Structure charts, data-flow diagrams, top-down decompositionStructured design
Structured vs object-oriented, side by sideStructured vs object-oriented
When functions and pipelines beat classesWhen procedural wins
Roles and stereotypes: information holder, structurer, service provider, controller, coordinator, interfacerResponsibility-driven design
Information expert, creator, low coupling, high cohesionAssigning responsibilities (GRASP)
Association, aggregation, composition, dependency, inheritance, realizationClass relationships
Small interfaces, "accept interfaces, return structs", PHP interface plus final classInterfaces and contracts
Command-query separation, parameter objects, return types, errors vs exceptionsMethod design
Constructors that enforce invariants, validation at the boundaryState and invariants
Seams, dependency injection, clocks and randomnessDesigning for testability
Maps vs slices, complexity awarenessData structures at class level
Service-local models, DTOs, anti-corruption layerLLD inside a microservice
clarify, entities, relationships, APIs, scenario, extendThe LLD interview method
Parking lot and notification system, completeSolving the classic problems
Wrong beliefs, cheat sheet, self-check, every termMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

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

TermIn plain wordsTiny exampleWhat goes wrong without it
Low-level design (LLD)Classes, functions, relationships and contracts inside one componentLot, Ticket, FeePolicy for a parking serviceEveryone 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 designDecompose by procedure; data and code are separateA call tree of IssueTicket, fee, releaseSpotEvery procedure reaches into shared data
Object-oriented designDecompose by responsibility; data and behaviour togetherLot owns its spots and guards its rulesGod objects, or classes that are just records
ResponsibilitySomething an object knows, does, or decides"Computes the fee for a stay"Classes named after nouns but with no job
Role stereotypeA recurring kind of jobController, coordinator, service providerEvery class does a bit of everything
RelationshipHow two classes are connectedLot owns SpotsHidden ownership, leaks, surprise deletes
ContractWhat a method promises and requires"Exit returns the fee or ErrUnknownTicket"Callers guess; behaviour drifts
InvariantA fact that is always true about an object"A cart has at most 10 lines"Invalid objects travel through the program
SeamA place where behaviour can be swapped without editing codeClock interfaceTests 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).

StepQuestionOutput
1. ClarifyWhat must it do, for whom, how big, what is out of scope?5 to 8 requirements
2. EntitiesWhich nouns carry state or rules?A candidate class list
3. RelationshipsWho owns, uses, or implements whom?A class diagram
4. APIsWhat are the public methods and their errors?Signatures and contracts
5. ScenarioDoes one real request run through the design?A sequence you can read aloud
6. ExtendWhat happens when a rule or a channel is added?Seams and a list of what changes

Structured vs object-oriented in one table.

AxisStructured designObject-oriented design
Unit of decompositionProcedure (what happens)Class (who is responsible)
Main pictureStructure chart, data-flow diagramClass diagram, sequence diagram
DataPassed around, often visible to allOwned by the class that guards it
Variationif/switch in the procedurePolymorphism behind an interface
StrengthPipelines, scripts, transformationsLong-lived rules with many variants
WeaknessShared data couples everythingNeedless classes for simple flows
Typical inC, COBOL, shell, SQL scripts, Go main and handlersJava, C#, PHP domain code, Go types with methods

The six relationships.

RelationshipUML markGoPHP
Dependencydashed arrowparameter or local variablemethod argument
Associationsolid arrowfield holding a pointer or interfaceprivate property set in the constructor
Aggregationhollow diamond[]*B filled from outsidearray of B passed in
Compositionfilled diamond[]B created and owned insidenew B() inside the owner
Inheritancesolid line, hollow trianglenone; embed for reuseextends
Realizationdashed line, hollow triangleimplicit method setimplements

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 LLDDoing LLD
Fast start, first commit in an hourOne to two hours of thinking first
Structure is whatever the first feature neededStructure follows the responsibilities
Every new rule edits many filesA new rule has an obvious home
Tests need the database and the clockPure rules are tested with fakes
Reviews argue about styleReviews argue about responsibilities
Risk: tangled code that "works"Risk: over-design for a throwaway script
Structured design: structure chartObject-oriented design: class diagramParkingAppIssueTicketExitfindFreeSpotstoreTicketfeereleaseSpotData couples (arrows with a dot in Yourdon notation):size, spot index, ticket id, fee in cents flow between modules.Reading rule: top calls bottom, left to right.Data is a plain record; every procedure may touch it.Question it answers: what are the steps?Lot«interface»FeePolicy«interface»Clock«record»Ticketid, spotNo, enteredAtHourlyFee- free, open, fees, clock+ Enter(size) Ticket+ Exit(id) MoneyFee(size, stay) MoneyNow() timeReading rule: arrows are "knows about".Question it answers: who is responsible for what?

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 ​

  1. "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.
  2. "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.
  3. "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.

HLDLLD
ScopeWhole system or serviceOne component or one use case
UnitsServices, databases, queues, cachesClasses, functions, interfaces, packages
QuestionsScale, availability, data flow, protocolsResponsibilities, relationships, contracts, state
ArtifactsArchitecture diagram, capacity numbers, API listClass diagram, sequence diagram, signatures, invariants
Failure modeWrong boundaries, wrong data storeGod classes, leaky abstractions, untestable code
Interview nameSystem designMachine coding, OO design
Sibling chaptersSystem DesignThis page
text
     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            team

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

PictureShowsReads asUsed in
Structure chartModules as boxes, calls as lines, data and control passed on each callTop calls bottom, left to rightStructured 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 outStructured analysis
FlowchartControl flow, decisions, loopsExecution orderAlgorithms
Data dictionaryEvery data item and flow, definedLookupBoth

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.

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

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

DecisionStructured answerObject-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 arrayOnly the Lot that owns the spots
Adding weekend pricingEdit fee, add an ifAdd a WeekendFee type, choose it at construction
Testing the feeCall the functionCall the policy, no lot needed
Replacing the data storeEdit every procedure that touches itReplace one collaborator
Reading the codeFollow the call treeFollow the object collaborations
text
     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 unchanged

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

SituationBetter asWhy
Parse, filter, aggregate a fileFunctions over slicesNo state between steps; trivial to test
HTTP handler: decode, call, encodeFunction plus small interfacesOne request, no object lifetime
Nightly ETL jobFunction pipelineStages are independent and replaceable
Pricing with ten tariffs and exceptionsClasses behind an interfaceVariants change independently
Long-lived stateful thing (lot, session, connection pool)A type that guards its stateInvariants must live somewhere
Algorithms (sort, search, graph)Functions, genericsNo identity to model
Laravel report over a large tableQuery builder, Collection or LazyCollection pipelineThe database already does the work
text
     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 each

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

User interfacerControllerCoordinatorService providerStructurerExternal interfacerInformation holdertranslates UI eventsinto requestsHTTP handler, CLIdecides, directs otherobjects (use case)EnterParking actionreacts to an event bydelegating to othersDispatcherperforms work, offersa computing serviceFeePolicy, RateLimiterkeeps relationshipsbetween objectsLot: spot to ticket maptalks to another system,hides its APIPaymentGateway (ACL)knows and providesfactsTicket, Money, Recipientdashed: the structurer holds references to the information holderssolid: who asks whom while a request travelsReading order: left to rightis the life of one request.
StereotypeResponsibility in one lineParking lot exampleNotification exampleSmell if overdone
Information holderKnows and provides informationTicket, MoneyNotification, RecipientAnemic everything: all data, no rules
StructurerMaintains relationships between objectsLot's free-spot stacks and open-ticket mapThe channel list in orderA structurer that also computes
Service providerPerforms work, offers a serviceFeePolicy, HourlyFeeRateLimiter, one ChannelA service with hidden state
ControllerMakes decisions and directs othersThe use-case that handles "car arrives"The rule "security skips the limiter"Controller knows every detail (God object)
CoordinatorReacts to events by delegatingLot.Enter calling stacks and clockDispatcherCoordinator that also does the work
InterfacerTransforms information and requests between partsHTTP handler, PaymentGateway ACLEmailChannel talking to SMTPBusiness 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).

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

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

GRASPQuestionShort answerExample here
Information expertWho should do this?The class that has the needed informationHourlyFee computes the fee: it owns the rates
CreatorWho creates object A?The class that contains, records, closely uses, or has the data for ALot creates Tickets
ControllerWho receives a system event?A non-UI object for the use caseEnterParking action
Low couplingHow to keep changes local?Prefer few, one-way dependenciesLot knows two small interfaces
High cohesionHow to keep classes focused?Responsibilities that belong togetherRateLimiter only limits
PolymorphismHow to handle variants by type?Put the variation behind an interfaceChannel, FeePolicy
Pure fabricationWhat if no domain class fits?Invent a service classDispatcher, Clock
IndirectionHow to decouple two things?Put a mediator between themPaymentGateway between service and provider
Protected variationsHow to shield from change?Wrap the unstable point behind a stable interfaceACL around a provider API
text
     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 rate

Fix: 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:

NotationRelationship, what it meansGoPHPDependencyAssociationAggregationCompositionInheritanceRealizationuses it for one call, keeps nothingholds a reference for a long timewhole has parts; parts outlive itwhole creates and owns parts; they die with itis-a; substitutable subtype (LSP)implements a contractparam or local of type Bfield b *B or an interfacefield []*B from outsidefield []B built inside Anone; embed B (reuse only)implicit method set; var _ I = (*T)(nil)method argumentprivate B $b in ctorarray of B passed innew B() inside Aclass A extends Bclass T implements I
RelationshipLifetimeMeaningTestGo formPHP form
DependencyOne call"uses"If B changes, A's method may break; A keeps no referencefunc (r Report) Render(w io.Writer)render(\Closure $write)
AssociationLong, independent"knows"A has a field referring to Bcustomer *Customerprivate readonly Customer $customer
AggregationParts outlive whole"has" (shared)B is created elsewhere and passed inmembers []*Personarray $members of passed-in objects
CompositionParts die with whole"owns"A creates B and nobody else holds itlines []Line built in AddLinenew Line(...) inside Order
InheritanceType hierarchy"is a"Every B can be used where A is expected (LSP)not available; embed for reuseclass Circle extends Shape
RealizationType to contract"implements"T provides all methods of Iimplicit; var _ I = (*T)(nil)class T implements I
text
     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 leaked

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

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

LanguageIdiomWhere the interface livesImplementing it
GoSmall, consumer-defined interface; return concrete structIn the package that uses itImplicit; no implements
PHPinterface plus final class implementations; bind in the containerNext to the consumer (or in a Contracts namespace)Explicit implements; final blocks extension
LaravelContracts in Illuminate\Contracts\*, bound in service providersFramework or app namespacebind or singleton in a provider
Java, C#Interface per role, often one per serviceWith the implementation (default)Explicit
text
     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 unaffected

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

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

HabitRuleGoPHPWhy
Command-query separationA method is a command or a queryDrop() vs Peek()drop() vs peek()Queries are safe to call anywhere
Parameter objectGroup arguments that travel togetherSearchParams structreadonly class SearchParamsNamed, validated, extensible (Fowler: Introduce Parameter Object)
No boolean flagsTwo behaviours, two methods or two typesRender and RenderPDFsameA flag means two jobs
Return type honestyReturn what you mean(T, error), (T, bool)?T, T or throwCallers cannot ignore absence
Failure as value (Go)Return error, wrap with %werrors.Is, errors.Asn/aExplicit control flow
Failure as exception (PHP)Throw domain exceptions, catch at the boundaryn/athrow new OutOfStockKeeps the happy path clean
Context first (Go)ctx context.Context is the first parameterSearch(ctx, p)n/aCancellation and deadlines
Few parametersThree or fewer; more means an objectNewLot(cap, fees, clock)constructor promotionReadability
text
     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 exception

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

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

TechniqueGoPHP 8.4Notes
Constructor that validatesfunc NewMoney(c int64, cur string) (Money, error)__construct throws InvalidArgumentExceptionGo returns the error; PHP throws
Unexported fieldslowercase fieldsprivate or readonly propertiesPackage-level privacy in Go
Immutabilityvalue receiver returning a new valuefinal readonly classSafer to share, no defensive copy
Zero-value strategyMake the zero value useful or unrepresentableTyped properties without default are uninitialisedvar m Money should not be a valid amount by accident
Enums for closed setsnamed int type with constantsenum Size: intIllegal states impossible
Boundary validationdecode, then constructForm Request, then new Email(...)Rules once at the edge
Database mirrorCHECK, UNIQUE, partial indexsameLast line of defence, concurrency-proof
text
     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 duplicate

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

go
// 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 dependencySeamGoPHP / Laravel
Current timeClock interfaceNow() time.Time, fakeClockClock interface, or travelTo() and freezeTime() in tests
RandomnessFunction valuetype IntN func(n int) intClosure or a Randomizer interface
DatabaseRepository interfaceconsumer-side userFinderinterface bound in a provider; or an in-memory fake
HTTP callSmall client interfaceDoer with Do(req)Http::fake()
Mail, SMSChannel interfacefake channel counting sendsNotification::fake(), Mail::fake()
Global stateConstructor parameterpass the config structconfig() read in the provider, not in the domain
IDsIDGenerator functionfunc() stringStr::uuid() behind an interface
text
     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.

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

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

NeedStructureCostGoPHP
Find by IDHash mapO(1) averagemap[TicketID]entryarray<string, Ticket>
Ordered iteration, small nSliceO(n) scan, cache-friendly[]Channellist<Channel>
Take the latest free itemStack (slice used as LIFO)O(1) push and popfree[size] stackarray_pop
Smallest or largest firstHeapO(log n)container/heapSplHeap, SplPriorityQueue
Membership testSet (map[T]struct{})O(1) averagemap[string]struct{}array_key_exists, isset
Sliding window, FIFOQueue, ring bufferO(1)slice with head indexSplQueue
Sorted range queriesSorted slice plus binary searchO(log n) search, O(n) insertsort.Searcharray + custom
Rate limiting per keyMap of token bucketsO(1) per callmap[string]*bucketcache keys (RateLimiter)
text
     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:

ConceptMeaningRule
Service-local modelThe domain classes inside one serviceNever exported as a shared library
DTO (Data Transfer Object)A flat structure for the wire or a boundaryNo behaviour; mapped to and from the model
Mapper / translatorCode that converts DTO to modelOne 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 contractOpenAPI, protobuf, message schemaVersioned; backward compatible
Domain eventsFacts the service publishesPast tense, small, stable
text
     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} only

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

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

StepMinutes (of 45)What you doWhat you sayOutput
1. Clarify5Ask 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. Entities5Underline nouns; keep those with state or rules; drop the rest"Lot, Spot, Ticket, Size; payment is a FeePolicy"Candidate classes
3. Relationships8Decide ownership and direction; mark interfaces"Lot owns Spots (composition) and depends on FeePolicy"Class diagram
4. APIs8Write signatures and the errors each may return"Enter(size) (Ticket, error); ErrFull"Method list
5. Walk a scenario10Run one happy path and one failure through the design"Car arrives, lot full, small car takes a medium spot..."Spoken sequence
6. Extend7Add a requirement; show where it plugs in"Weekend pricing is a new FeePolicy; the lot is unchanged"Seams and trade-offs
7. Wrap up2State trade-offs, concurrency, persistence, what you skipped"In-memory here; a unique index makes it safe across nodes"Honest limits
text
     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 built

What 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 frameworkUnit of designInterfacesInheritanceErrorsNatural LLD style
GoPackage, then type with methodsImplicit, small, consumer-ownedNone; embedding for reuseerror values, errors.Is/AsSmall types, plain functions, interfaces at seams
PHP 8.4Class in a namespaceinterface, explicitextends, abstract, finalExceptionsValue objects, services, enums, readonly classes
Laravel 13Framework slots (Action, Request, Policy, Job, Notification)Contracts bound in the containerModels extend Eloquent; avoid elsewhereExceptions plus the exception handlerThin slots around domain classes
JavaClass in a packageExplicit, often one per serviceCommon, shallow is betterChecked and unchecked exceptionsClass-per-role, builders, DI frameworks
C#Class in a namespaceExplicitCommonExceptionsSame as Java, records for DTOs
PythonModule, classProtocols or ABCsMultiple inheritance possibleExceptionsDataclasses plus functions
TypeScriptModule, class, typeStructural typesextendsExceptions or result typesTypes and functions over class hierarchies
C, COBOL, shellProcedure, fileHeader filesNoneReturn codesStructured 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.

ClassRoleResponsibilities (verbs)CollaboratorsKnows (state)
LotCoordinator + structurerAllocate a spot, release a spot, issue a ticket, report free countFeePolicy, Clock, spotFree stacks, open tickets
TicketInformation holderCarry id, spot and entry timenoneId, spot, time
FeePolicyService providerCompute a fee for a staynoneRates
ClockService providerTell the timenonenone
DispatcherCoordinatorChoose channels, apply rate limit, fall backChannel, Preferences, RateLimiterChannel order
ChannelService provider / external interfacerDeliver one messageSMTP, SMS gatewayCredentials
RateLimiterService providerAllow or deny per keyClockBuckets
PreferencesInformation providerAnswer "may I send this?"databaseUser settings

Checking a design: the five questions Must-know ​

QuestionPassFail signalRepair
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 fakeClockNeeds database to test a ruleExtract the rule, inject the store
Does a new variant add a class instead of editing one?WeekendFeeNew if in fee()Interface plus implementation
Does a change stay local?One fileShotgun surgeryMove the responsibility (Move Method)
Is state guarded by one owner?Lot alone edits spotsSeveral classes flip takenEncapsulate, narrow the API

Walking a scenario Must-know ​

text
     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)  -> 1

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

OperationParking LotNotification DispatcherWhy
CreateO(spots) onceO(channels) onceConstructors do the setup
Main actionEnter: O(sizes), here at most 3Send: O(channels)Stacks and a short list
ReleaseExit: O(1)n/aMap lookup plus push
QueryFree: O(1)n/alen of a slice
MemoryO(spots + open tickets)O(users) for bucketsEvict idle buckets in production
ConcurrencyOne mutex around the lotOne limiter per processContention is the first scaling limit

Go ​

Example: structured and pipeline style ​

The structure chart from the diagram, written as Go: records plus procedures.

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

go
// 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), not utils or common.
  • 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 with errors.Is. See Error and Exception Handling.
  • Concurrency inside a type. A sync.Mutex field 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.DB plus driver interfaces behind it). golang.org/x/time/rate is a token-bucket Limiter: "a token bucket of size b, initially full and refilled at rate r tokens per second", created with rate.NewLimiter(rate.Every(time.Second), 5) and used through Allow, AllowN, Wait.

Laravel ​

Example: the same ideas in PHP 8.4 ​

Structured style first (functions over arrays), then the pipeline with Collection:

php
<?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
<?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
<?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

// 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
<?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
<?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 valid

Testability and the anti-corruption layer:

php
<?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
<?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 class and enum make 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) fake now() for the whole framework; a Clock interface is still the cleaner design for domain classes that should run without Laravel.
  • Notifications. A notification class declares channels in via(object $notifiable): array and one toMail, toDatabase, ... method per channel; add implements ShouldQueue to queue delivery. Use Notification::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, availableIn and clear store 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.

LotSpotTicket «record»FeePolicyClockHourlyFeeSystemClockSize «enum»«interface»«interface»- mu, nextID- free map[Size][]spot+ Enter(Size) (Ticket, error)+ Exit(TicketID) (Money, error)- no int- size Size+ ID, SpotNo, Size+ EnteredAtFee(Size, Duration) MoneyNow() TimePerHour map[Size]MoneySmall, Medium, Large1..*0..* openfeesclockcompositionassociationdashed + hollow triangle = realization

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.

MethodContractErrors
NewLot(capacity, fees, clock)At least one spot, known sizes, non-nil collaboratorserror describing the violation
Enter(size) (Ticket, error)Gives the smallest free spot that fits; one ticket per callErrFull
Exit(id) (Money, error)Frees the spot, returns the fee for started hoursErrUnknownTicket (also for a second exit)
Free(size) intQuery; never changes statenone

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):

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

go
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
<?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:

sql
-- 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;
SolutionHowAdvantageCost or limit
One mutex in the Lotsync.Mutex around Enter and ExitSimple, correct for one processOne process only; contention at high rates
Unique partial indexDatabase rejects a second open ticket per spotCorrect across processesNeeds a retry on conflict
FOR UPDATE SKIP LOCKEDWorkers skip rows locked by othersNo waiting, no deadlock between workersQuery shape must stay as above
Per-floor lotsShard by floorLess contentionMore 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.

DispatcherNotificationRecipientPreferencesChannelRateLimiterClockPrefsStoreEmailSMSPush«interface»«interface»«interface»- channels []Channel (preference order)- prefs, limiter+ Send(ctx, to, n) (via string, err)Kind, Subject, BodyUserID, Email, PhoneAllows(user, kind, channel) boolName() stringSend(ctx, to, n) error- buckets map[user]*bucket+ Allow(key) boolNow() Timereads user settingsdashed + hollow triangle: realizes Channelprefschannels 1..*limiterclock

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.

MethodContractErrors
NewDispatcher(prefs, limiter, channels...)Non-nil collaborators, at least one channelconstruction 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 limiterErrRateLimited, ErrNoChannel joined with each channel failure
Channel.Send(ctx, to, n) errorDeliver or fail; must respect ctxany error
Preferences.Allows(user, kind, channel) boolQuery; no side effectsnone
RateLimiter.Allow(key) boolTakes one token if availablenone
text
     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):

go
// 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...)...)
}
go
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
<?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));
AlternativeWhenTrade-off
Dispatcher with explicit channel list (above)Custom fallback, preferences, limitsYou build and test the coordinator
Laravel Notification with via()Standard email, database, broadcast, SlackFallback and preference logic go in via() or a custom channel
Queue per channelHigh volume, slow providersEventual delivery, ordering across channels is lost
One message per channel plus an outboxMust not lose a notificationMore moving parts, exactly the outbox cost

Other classic problems ​

ProblemSmell in the first draftResponsibility-based fix
Manager or Helper class that does everythingMany unrelated methods, many collaboratorsSplit by role: coordinator, service providers, holders
switch on a type string in many placesAdding a variant edits several filesInterface per variant, choose once at construction
Primitive obsession (string email, int cents everywhere)Validation repeated, units mixedEmail, Money value objects with invariants
Anemic records plus a giant serviceRules far from the dataMove behaviour next to the data it guards (information expert)
Hidden time.Now() / now() / new Mailer()Slow, flaky testsInject Clock, Channel
Interface per class "for mocking"Parallel hierarchy, no consumerCreate the interface where it is consumed, when needed
Deep inheritance to share codeFragile base classComposition; small interface plus helper
Public mutable fieldsInvariants broken anywhereUnexported fields, methods that guard

Choosing: which structure for which problem ​

ProblemRecommended structureExtra techniqueReason
Transformation of data (parse, filter, aggregate)Functions and slices or CollectionTable-driven testsNo state, no variants
Rule-heavy domain with variants (pricing, discounts)Classes with an interface per variantConstruct the variant once, inject itVariants change independently
Long-lived stateful object (lot, session, pool)A type guarding its stateConstructor invariants, mutexThe rules need an owner
Integration with a foreign systemGateway interface plus translator (ACL)DTO at the boundaryKeeps foreign vocabulary out
Variation by configuration onlyOne type with a parameterValidate at constructionA class per value is noise
Many channels or plug-ins, new ones monthlyInterface plus registry or listContract testsAdd by adding a type
One caller, one implementation, unlikely to changeConcrete type, no interfaceAdd the interface when the second need appearsAvoid speculative abstraction (YAGNI)
Throwaway scriptOne functionNothingCost of structure exceeds the benefit
HeuristicSay yes to a new class whenSay no when
ResponsibilityIt has a verb the others do notIt only forwards calls
VariationTwo variants exist todayOne variant "might come"
StateIt guards an invariantIt is a bag of getters
TestingIt removes a hard dependency from testsIt 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.

RuleWhy
A module exposes a facade and DTOs, not entitiesEntities carry invariants other modules should not touch
A module owns its tables; others read through the facade or an eventOne writer per table
Cross-module calls are interfaces defined by the callerThe 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."

text
     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
ConcernRule
Shared classes between servicesNo. Share schemas (OpenAPI, protobuf), not code
DTO vs domain modelSeparate types, mapped at the boundary
Foreign vocabularyACL per foreign system
IdsReference other services' entities by id, not by object
Failure of a collaboratorThe 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.

FailureCauseLLD answer
Double allocationPer-process state, two nodesMove the invariant to the database (unique index, row lock)
Limit multiplied by node countPer-process countersShared store (Redis) or edge limiter
Stale preferencesCache without invalidationShort TTL, versioned key, or accept and document
Duplicate notificationAt-least-once delivery from the queueIdempotent Send keyed by notification id (see Idempotent Consumers)
Clock skew between nodesDifferent Now() per nodeTake time from the database or one source for ordering decisions

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

ScaleStructureLLD practice
1× (one team, one app)A few packages, concrete types, interfaces only at seamsOne-page LLD, constructor injection, fake clock
10× (several teams, modular monolith)Modules with facades and consumer-owned interfacesArchitecture tests, DTOs between modules, unique indexes for invariants
100× (many services, many deploys)Service-local models, ACLs, published schemasContract tests, idempotent handlers, per-service LLD docs and ADRs
AnyReassess the LLD when a change touches more than one moduleMove 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.

bash
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, testability

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

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

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

MetricStructuredObject-oriented
Files touched to add weekend pricing1 (plus all callers of fee)1 new type, 0 edits to Lot
Test of the fee in isolationneeds a lot or a copy of feeWeekendFee{...}.Fee(...) alone
Cost of finding a ticketmap lookupmap lookup
Where the "taken" flag is changedIssueTicket, releaseSpotonly Lot

Common misconceptions ​

BeliefReality
"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 ​

TopicWhat to remember
LLD vs HLDHLD picks the boxes; LLD designs inside one box
Structured designCall tree of procedures; structure chart; data couples; top-down
OO designResponsibilities with owned data; class diagram; polymorphism for variants
Procedural winsPipelines, handlers, scripts, algorithms
Role stereotypesInformation holder, structurer, service provider, controller, coordinator, interfacer
GRASP first questionInformation expert: give the job to whoever has the data
OwnershipComposition owns; aggregation shares; association knows; dependency uses
InterfacesSmall, consumer-owned; Go: accept interfaces, return structs; PHP: interface plus final class
MethodsCommand or query; parameter object after three arguments; name the failures
InvariantsConstructor establishes, methods preserve, fields private, DB constraint last
TestabilityInject Clock and randomness; fake at seams, not everywhere
Data structuresMap for lookup by id; stack for latest free; state the cost
Interview methodClarify, entities, relationships, APIs, scenario, extend, limits
Microservice LLDService-local model, DTO at boundary, ACL for foreign systems
Distributed statePer-process state does not scale out; move invariants to the database

Self-check: questions & answers ​

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

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

TermMeaning
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 designSWEBOK's name for the design stage that LLD covers
Structured designDecomposition by procedure, with data and code separate (Yourdon and Constantine)
Structure chartTree of modules with the data passed on each call
Data-flow diagram (DFD)Processes, stores, entities and data flows, without control flow
Top-down decompositionSplitting a task into steps, then each step into smaller steps
Stepwise refinementWirth's name for top-down decomposition by successive detail
Data coupleA module passes simple data to another; the loosest coupling in the 1974 paper
Object-oriented designDecomposition into objects that combine state and behaviour
ResponsibilitySomething an object knows, does, or decides
CollaboratorAnother object a class asks for help
Responsibility-driven designWirfs-Brock and Wilkerson's method: design by contracts and responsibilities
CRC cardClass, Responsibility, Collaborators card (Beck and Cunningham, 1989)
Role stereotypeA recurring role: information holder, structurer, service provider, controller, coordinator, interfacer
Information holderRole that knows and provides information
StructurerRole that maintains relationships between objects
Service providerRole that performs work and offers a service
ControllerRole that makes decisions and directs others
CoordinatorRole that reacts to events by delegating
InterfacerRole that transforms information and requests between parts, or to another system
GRASPLarman's nine principles for assigning responsibilities
Information expertGRASP: give the job to the class that has the information
CreatorGRASP: who creates an object
Pure fabricationGRASP: an invented class that has no domain counterpart
IndirectionGRASP: put a mediator between two things
Protected variationsGRASP: wrap an unstable point behind a stable interface
DependencyUses another class for one call and keeps nothing
AssociationA class holds a long-lived reference to another
AggregationWhole-part with shared lifetime semantics; parts outlive the whole
CompositionWhole-part where the whole owns the parts and they die with it
InheritanceSubtype relationship (is-a); not available in Go
RealizationA type implements an interface or contract
EmbeddingGo's reuse mechanism: a struct field promotes the embedded type's methods; not subtyping
ContractThe preconditions, postconditions and failures of a method or interface
Accept interfaces, return structsGo idiom: parameters are small interfaces, results are concrete types
final classPHP class that cannot be extended
readonly classPHP 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 objectA type that groups arguments that travel together
InvariantA condition that is always true about an object after any public call
Value objectAn immutable object compared by value (Money, Email)
Boundary validationConverting untrusted input into valid objects once, at the edge
SeamA place where behaviour can be replaced without editing the code there
Dependency injectionSupplying collaborators from outside, usually through the constructor
FakeA simple working substitute for a dependency (fake clock, in-memory store)
Token bucketRate-limiting structure: a bucket of tokens refilled at a fixed rate; one per request
Sentinel errorA package-level error value compared with errors.Is
Service-local modelThe 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
FacadeOne narrow entry point to a module
God classA class with many roles and many reasons to change
Anemic modelClasses that hold data only, with rules in separate services
Primitive obsessionUsing raw strings and integers where a domain type belongs

References ​

Built by Morteza Negahi