Skip to content

Anemic vs Rich Domain Models ​

"In essence the problem with anemic domain models is that they incur all of the costs of a domain model, without yielding any of the benefits." — Martin Fowler, bliki "Anemic Domain Model" (25 November 2003)

Summary: An anemic model keeps data in objects and rules in services; a rich model keeps the data and the rules that protect it in the same object. Neither is a sin by itself: pick the pattern by subdomain (Transaction Script and Active Record for simple supporting and generic areas, Domain Model for a core area, event sourcing when history is the value) and move the invariants of a core domain into the model. Focus: Definitions, why anemia happens (ORMs, CRUD frameworks, layering habits), Fowler's argument and its counter-arguments, the spectrum from Transaction Script to event-sourced Domain Model, the costs of anemia and of forced richness, Tell-Don't-Ask, illegal states, three Eloquent strategies, Go structs with unexported fields, testing differences, a behaviour-preserving refactoring of the running Order, and how to measure where the invariants live. Learning goal: Given a service-plus-setters design, say which subdomains deserve a rich model, move the cancel rule into an Order aggregate in Go and Laravel behind a characterization table, close the illegal-state holes (types, state machine, CHECK), and defend the choice with two numbers: where the invariants live and how many tests need a database.

This chapter belongs to group DD 02 (Tactical Design). It assumes the building blocks (Entities & Value Objects, Aggregates & Factories) and the subdomain types (Domains & Subdomains). It owns one question: where does the business rule live, in the object or beside it? The neighbours own the rest: how objects are loaded and saved (Repositories, Data Persistence in Design), what the three service kinds are (Domain, Application & Infrastructure Services), what the model announces (Domain Events vs Integration Events), the object-oriented basics (Object-Oriented Modeling), and how the model survives a service boundary (Service Boundaries, Outbox, Saga).

Page map ​

If you are looking forGo to
The whole page in four tablesEverything in one minute
What problem the choice solvesWhy the choice exists
Fowler, Evans, Vernon, Khononov, Three Dots LabsWhere it comes from
The two definitions side by sideWhat it is
Anemic model, preciselyThe anemic model
Rich model, preciselyThe rich model
ORMs, frameworks, layering habitsWhy anemia happens
Fowler's case and the fair objectionsFowler's argument and the counter-arguments
Transaction Script to event-sourcedThe spectrum
Bug stories and where they come fromThe costs of anemia
Ceremony in simple areasThe costs of forced richness
Tell-Don't-Ask, encapsulationTell, don't ask
Entity vs domain service vs application serviceWhere does the logic go
State machines, enums, value objectsIllegal states
Eloquent models and the three strategiesEloquent and anemia
Exported fields, packages per contextGo and anemia
Tests with and without a databaseTesting
Two numbers to trackMeasuring
Hydration, bypass paths, CHECKMechanics
Before/after codeGo, Laravel
Refactoring stepsSolving the classic problems
Which pattern for which areaChoosing
Monolith to distributedIn architecture
Hands-onLab
Wrong beliefs, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The two shapes. Every row is unpacked later.

Anemic modelRich model
Where the data isIn objects with public fields or getters and settersIn objects with private state
Where the rules areIn services (OrderService.Cancel)In the object (order.Cancel)
Who protects an invariantEvery caller, by rememberingThe object, by construction
Can an invalid object existYes, any setter call makes oneNo, a constructor and methods refuse it
Test without a databaseRarely, the rule hides behind load and saveYes, call the method
FitsSimple, supporting and generic areasCore areas with real rules
Fowler's name for itTransaction Script wearing an object costumeDomain Model

The spectrum (details in the spectrum).

PatternPlain wordsSubdomain it fitsTiny example
Transaction ScriptOne procedure per requestSupporting, generic, simpleSaveProductNote(sku, body)
Table ModuleOne object handles all rows of a tableData-centric reports, .NET-style recordsetsOrderTable.TotalFor(rows)
Active RecordA row object that saves itself and holds a few rulesSupporting with light rulesAn Eloquent Order with cancel()
Domain ModelObjects with identity and behaviour; the database is behind a mapperCore with complex rulessales.Order aggregate
Event-sourced Domain ModelState is the fold of recorded eventsCore where the history is the valueA ledger or an audit-heavy workflow

The costs.

CostHappens whenSymptom
Scattered invariantsRules live in servicesSupport tool cancels a dispatched order
Duplicated validationEach entry point copies the checkController, import and API disagree
Impossible statesPublic setters, free-text statusstatus = 'canceled' in the table
Integration-heavy testsRules need load and saveSlow suite, tests need Docker
CeremonyA rich model forced on a simple areaSix classes to save a note
Mapper taxDomain objects separate from rowsMore code per feature, more mapping bugs

Two numbers to track (details in Measuring).

MetricHowHealthy sign
Where invariants liveGrep for the rule (dispatched) across the repoOne match in the domain, plus one CHECK
Tests that need a databaseCount tests that open a connection or fake a repositoryCore rules tested with no store at all

Why the choice exists ​

A business rule has to live somewhere. Putting it in the object that owns the data makes it impossible to forget; putting it in a service makes it easy to write and easy to copy. The first costs design effort up front, the second costs bugs later. Which price is smaller depends on how many rules there are and how much they matter.

Procedural (anemic)Object-oriented (rich)
Cheap to start, matches the tableNeeds a model and a mapper
Rules grow in services, copies driftRules grow in the object, one copy
Easy to read one use case top to bottomNeeds reading the object to see the rules
Any caller can corrupt stateObject refuses invalid transitions
Good for 5 rulesGood for 50 rules

The everyday analogy. A bank vault with a very honest, forgetful clerk. The anemic version is an open room with money on the table and a laminated card of rules the clerk checks "when they remember". The rich version is a vault door that only opens in the right sequence. The vault is more work to build. For a petty-cash drawer, the card is enough.

Three common misunderstandings, up front ​

  1. "Anemic is always wrong." Fowler himself says Domain Models are not always the best tool. A Transaction Script is the right pattern for simple areas (the spectrum).
  2. "Rich means putting everything in the entity, including SQL and HTTP." Fowler says domain logic belongs in the object, persistence and presentation do not. A rich object has no save(), no request, no logger.
  3. "A service layer proves the model is anemic." An application service (Fowler's Service Layer) is thin and fine. The sin is domain rules in the service while the object is a bag.

Where it comes from ​

YearSourceWhat it contributed
2002Fowler, Patterns of Enterprise Application Architecture, ch. 9Names Transaction Script, Table Module, Domain Model, and Service Layer (Randy Stafford); Active Record (ch. 10)
2003Eric Evans, Domain-Driven DesignModel-driven design, entities, value objects, services, aggregates; "give up too easily on fitting the behavior into an appropriate object"
2003Fowler, bliki "Anemic Domain Model", 25 November 2003The anti-pattern: objects that at first blush "look like the real thing" but have "hardly any behavior"
2012Robert C. Martin, "The Clean Architecture" (13 August 2012)Entities hold enterprise-wide rules; use cases orchestrate
2013Vaughn Vernon, Implementing Domain-Driven Design, ch. 1Warns about anemia and "DDD-lite" that takes the vocabulary without the model (secondary source here, not fetched)
2013Fowler, bliki "Tell Dont Ask" (5 September 2013)Bundle data with the behaviour that uses it
2015Evans, DDD ReferenceServices pattern: use a service only when an operation is "not a natural responsibility of an entity or value object"
2019Alexis King, "Parse, don't validate" (5 November 2019)Make illegal states unrepresentable
2020Three Dots Labs, "DDD Lite" in Go (Wild Workouts)Go types with behaviour, private fields, packages per context
2021Vlad Khononov, Learning Domain-Driven DesignPicks the logic pattern by subdomain type (secondary source here, not fetched)

Primary quotes read for this page (saved text, see References). Fowler: "The fundamental horror of this anti-pattern is that it's so contrary to the basic idea of object-oriented design; which is to combine data and process together." Fowler on the counter-position: "As I discussed in P of EAA, Domain Models aren't always the best tool." Fowler quoting Evans: "the more common mistake is to give up too easily on fitting the behavior into an appropriate object, gradually slipping toward procedural programming." Three Dots Labs: "The only public API of the object should be methods describing behaviors. No dumb getters and setters!"

What it is ​

Where does the business logic live?Transaction Scriptone procedure per requestrows or plain structsActive Recordrow object witha few methods + save()Domain Modelaggregates enforceinvariants; no DB insideEvent-sourcedDomain Modelstate = fold of eventsSupporting / generic subdomainsimple rules, buy or keep it cheapCore subdomaincomplex rules, competitive edgerising complexity of the business rules, rising modelling effortHeuristic after Khononov (secondary source); Fowler: Domain Models are not always the best tool

Fowler's definition of the symptom: at first blush the model "looks like the real thing" (nouns of the domain, rich relationships) but has "hardly any behavior", "little more than bags of getters and setters", and the rules sit in "a set of service objects" that use the model "for data".

PartAnemicRich
ObjectData bag: exported fields, getters/setters, public constructor with no checksBehaviour with state: methods named after business verbs
Constructionnew Order() then assignNewOrder(id, customer, currency) returns an error for invalid input
State changeorder.Status = "cancelled"order.Cancel(reason, now)
ValidationIn the service, per use caseIn the constructor and methods, once
ServicesHold the domain rulesOrchestrate: load, call, save, publish
Persistence shapeThe object is the rowThe object is a model; a mapper owns the row

The concept catalogue ​

The anemic model Must-know ​

In plain words: The Order class has a field for everything and a rule for nothing. Somewhere else a OrderService knows what a legal order looks like and edits the fields.

Common misunderstanding: "If the classes have the right names and relationships, it is a domain model." Fowler: the catch "comes when you look at the behavior". Names and a diagram are not a model; rules are.

Definition: A domain model whose objects hold state only, with the domain logic (validations, calculations, business rules) in service objects layered above. In Fowler's words, "you essentially end up with Transaction Scripts" but you still pay for the object-relational mapping layer.

 anemic order cancel (one entry point)
 1  controller        -> OrderService.Cancel(id, reason)
 2  OrderService      -> repo.Get(id)                 // loads a bag of fields
 3  OrderService      -> if bag.Status == "dispatched" -> error      // rule, copy 1
 4  OrderService      -> bag.Status = "cancelled"     // plain assignment
 5  OrderService      -> repo.Save(bag)
 later:
 6  SupportController -> bag.Status = "cancelled"     // rule, copy 2, without the dispatched check

Real scenario: An Eloquent Order with $guarded = []; a Go struct type Order struct { Status string; Total int64 } with a Total that is stored and recomputed in three places; a Java POJO with Lombok @Data and a OrderManager.

SignalAnemicNot necessarily anemic
Public setter for every fieldYesA DTO or a read model may be
Status is a free stringYesA legacy column mapped by an ACL
Services named OrderManager, OrderProcessor, OrderHelperOftenApplication services with thin bodies are fine
if order.Status == in many filesYesOne match in the domain is fine
Domain objects imported by every layerOftenA shared kernel of value objects is fine

Fix / how to use it: Solving the classic problems refactors it; the next block shows the target.

The rich model Must-know ​

In plain words: The Order knows what it is allowed to do. You ask it to Cancel and it either does it or tells you why not. Nobody else can change its state.

Common misunderstanding: "A rich model means all logic in the entity." Logic that belongs to one object goes there; logic that spans several aggregates or needs outside information goes to a domain service; orchestration goes to the application service (where does the logic go).

Definition: Objects with identity and behaviour whose state can change only through methods that preserve their invariants. Fowler (PoEAA): Domain Model is "an object model of the domain that incorporates both behavior and data". An invariant is a rule that must be true after every command, for example "a dispatched order is never cancelled".

 rich order cancel
 1  controller        -> CancelOrderHandler.Handle(id, reason)
 2  handler           -> repo.Get(id)                  // restores an Order, rejects broken rows
 3  handler           -> order.Cancel(reason, now)     // rule checked here, once
 4  order             -> state machine: dispatched -> error; paid -> cancelled + refundDue
 5  handler           -> repo.Save(order)
 6  handler           -> publish(order.PullEvents())   // OrderCancelled { RefundDue: true }
 later:
 7  SupportController -> same handler, same rule

Real scenario: sales.Order in the chapter code; Three Dots Labs' Hour.ScheduleTraining() which returns ErrHourNotAvailable; a Subscription.Pause() that refuses to pause a cancelled subscription.

PropertyRich model givesHow
Always validNo invalid object existsConstructor returns error; no setters
Single source of truthOne copy of each ruleMethod on the object
Business languageCancel, Place, MarkPaidUbiquitous language
TestableUnit test, no I/OCall the method, inspect state and events
EvolvableA new rule edits one fileMethods, not call sites

Fix / how to use it: Go and Laravel show full code.

Why anemia happens Must-know ​

In plain words: The tools, the habits and the first tutorials all point toward "table → class with fields → service that edits them". It is the path of least resistance.

Common misunderstanding: "Anemia comes from lazy developers." It comes from honest, local decisions: each one makes sense and the sum is a procedural system. Fowler writes "I don't know why this anti-pattern is so common" and guesses people "who haven't really worked with a proper domain model" and "technologies" that "encourage it", J2EE Entity Beans in his example.

Definition: The recurring causes of anemia:

CauseHow it pushes toward anemiaCounter
ORM and generated entitiesOne class per table with public fields (Hibernate beans, Eloquent $guarded = [], sqlc structs)Treat the generated type as persistence only; build the model separately where it matters
CRUD frameworks and scaffoldingphp artisan make:model -mcr gives a model, a controller, a migration: no place for rulesAdd the application step and domain methods
Layering habits"Controllers call services, services call repositories": every class gets a layer, none gets a rulePut rules in the domain layer, keep services thin
"Services do things"Verbs become service methods, nouns stay dataVerbs of the language become methods on the noun
Data-first thinkingThe schema is designed first; classes mirror itModel behaviour first, then persistence (Data Persistence in Design)
Fear of fat modelsEloquent "fat model" folklore leads to "thin models, fat services"Fat in the wrong place is bad; rules in the right place is design
Team boundariesBackend owners write services, DBAs own tablesA model owner per context
Framework tutorialsShow $order->status = 'x'; $order->save();Show the method instead
Testing convenienceA service with mocks is "easy" to testA method on an object needs no mocks
 how anemia grows (a composite, typical history)
 1  month 1   OrderService.Cancel   copies the rules from the spec
 2  month 4   mobile API            writes its own cancel (copy 2, without refund)
 3  month 9   support tool          writes force-cancel (copy 3, without dispatched check)
 4  month 14  CSV import            sets Status directly (no check at all)
 5  month 15  an audit finds 41 dispatched orders in status cancelled

Real scenario: A start-up with a Laravel admin panel, a mobile API and a support tool, all editing orders.status; a Go service where sqlc generated Order structs are passed through all layers.

Fix / how to use it: The refactoring in Solving the classic problems.

Fowler's argument and the counter-arguments Must-know ​

In plain words: Fowler says an anemic model pays the cost of objects (mapping) and gets none of the benefit (behaviour). The fair reply: if there is almost no behaviour, objects are not worth it, and a script is the honest design.

Common misunderstanding: "Fowler forbids Transaction Scripts." He names the result "Transaction Scripts" and adds that "Domain Models aren't always the best tool". The attack is on pretending to have a model while paying its costs.

Definition: The argument has three parts, and each has a reply.

Fowler's claimIn his wordsThe fair reply
It is procedural design in an object costume"really just a procedural style design"True; fine if the area is simple and you do not pretend otherwise
It pays the model's costs without the benefits"all of the costs of a domain model, without yielding any of the benefits"The cost is mapping; you avoid it with Active Record or a plain script and no model
Services should be thin"The key point here is that the Service Layer is thin"Agreed; the fix is in the layering, not in a bigger entity
Slipping toward procedural is the common mistakeEvans, quoted by Fowler: "give up too easily on fitting the behavior into an appropriate object"Yes in core areas; elsewhere it is the correct economy

Counter-arguments practitioners make, with the honest status of each:

Counter-argumentStrengthWhy
"Functional style separates data and functions on purpose"StrongImmutable data plus pure functions is not anemia if the functions preserve invariants and construction validates. The test is still where do the invariants live
"Most business software is CRUD"StrongThen use Active Record or scripts and save the ceremony
"A rich model hurts when queries cross aggregates"MediumTrue; use CQRS read models for queries, keep the model for writes
"Setters are fine with validation attributes"WeakValidation on write paths you remember is not an invariant; direct field access, imports and updates bypass it
"Rich models are slower to build"MediumAt first yes; the cost reverses when rules multiply
"Our team does not know DDD"MediumStart with one aggregate; no big-bang

Real scenario: The PoEAA catalog entry for Domain Model begins with the situation it targets: "At its worst business logic can be very complex", and "it's this complexity that objects were designed to work with". Where the logic is not complex, that argument does not apply.

Fix / how to use it: Use Choosing to decide per subdomain, not per company.

The spectrum: from Transaction Script to the event-sourced model Must-know ​

In plain words: Domain logic has four common shapes, from "one function per button" to "state is a log". Pick the simplest one that still keeps the rules in one place.

Common misunderstanding: "The right end of the spectrum is the mature end." It is the expensive end. Using it on a supporting subdomain is waste, and using the left end on a core subdomain is debt.

Definition: The four patterns Khononov arranges as a progression (secondary source, not fetched; the first three are Fowler's PoEAA patterns):

PatternSourceMechanismStrengthWeakness
Transaction ScriptPoEAA: "Organizes business logic by procedures where each procedure handles a single request from the presentation"One procedure per use case, often wrapped in one database transactionSimple, fast, easy to readDuplication grows; every script re-implements shared rules
Table ModulePoEAA: "A single instance that handles the business logic for all rows in a database table or view"One object per table, operates on recordsetsFits recordset-oriented platformsHard to model identity and relationships
Active RecordPoEAA: "An object that wraps a row in a database table or view, encapsulates the database access, and adds domain logic on that data"Row object with save() and some rulesLow ceremony, fast to shipDomain tied to the schema; cross-row rules are awkward
Domain ModelPoEAA: "An object model of the domain that incorporates both behavior and data"Aggregates with invariants; a mapper handles persistenceComplex rules stay organisedMapper cost, more design effort
Event-sourced Domain ModelEvolution of Domain ModelState is derived from an append-only stream of eventsFull history, time travel, auditSteep learning curve; versioning, projections; see Event Sourcing & CQRS

Khononov's heuristic maps subdomain type and rule complexity to the pattern (secondary source; the mapping is the author's, paraphrased):

Subdomain typeRule complexityPatternWhy
GenericAny (you buy or reuse it)Use a library or product; if you must build, Transaction ScriptThe logic is not your edge
SupportingSimple, CRUD-shapedTransaction ScriptCheapest correct design
SupportingRows with light derived valuesActive RecordSlightly more structure, still cheap
CoreComplex rules, many statesDomain ModelRules are the product; invest
CoreHistory and audit are the productEvent-sourced Domain ModelTimeline matters as much as state
 deciding for each subdomain (Sales, Fulfilment, Billing, Catalog, Identity)
 1  Is it a core subdomain?            Sales ordering, Fulfilment planning -> yes
 2  Do the rules have many states?     Order: draft/placed/paid/dispatched/cancelled -> yes
 3  Choose                             Domain Model (Order aggregate) for Sales
 4  Catalog product notes              supporting, CRUD -> Transaction Script
 5  Identity (login, reset password)   generic -> Laravel Fortify/Breeze, do not model
 6  Billing ledger                     core-ish with audit -> consider event-sourced

Real scenario: Sales and Fulfilment get a Domain Model; Catalog admin screens use Eloquent Active Record; Identity uses a framework package; Billing's ledger is an append-only table (an event-sourced shape). See Domains & Subdomains.

Fix / how to use it: Choosing turns this into a per-area decision table.

The costs of anemia in a core domain Must-know ​

In plain words: The first copy of a rule is free. The second copy is a bug waiting to happen. The tenth copy is a rewrite.

Common misunderstanding: "We have tests on the service, so the rules are covered." The service test covers the service. The importer, the support tool and the next developer's update() do not call it.

Definition: In a core domain an anemic model has four recurring costs.

CostMechanismWhere it hurts
Invariants scatteredEach caller owns a private copyRule changes touch many files; one is missed
Duplicated validationSame check in controller, request class, service, importerCopies disagree about edge cases
Hard-to-test servicesThe rule is behind load, save and mocksSlow tests, brittle mocks, low confidence
Impossible states representablePublic setters, free-text statuses, stored totalsData nobody planned for reaches reports and billing

Four composite stories, each pattern seen often in systems like the running example (stories are illustrative, not reports about a named company):

StoryCauseEffectFix in this chapter
"The refunded parcel"SupportService.ForceCancel omitted the dispatched checkCustomer got the money back and the parcel arrivedOne Order.Cancel, all callers through the handler
"The ghost status"CSV import wrote canceled (one l)Report counted fewer cancellations; billing skipped themStatus enum and Restore rejecting unknown values; CHECK
"The negative line"Mobile API did not validate quantity; the web form didA -3 quantity reduced the total and passed paymentAddLine validates once; a CHECK (quantity BETWEEN 1 AND 50)
"The two totals"Total stored and also recomputed in two servicesInvoice and order screen showed different amountsTotal() derived from lines
 the refunded parcel (anemic, composite)
 1  T0    Order 1042 is paid and dispatched (status = "dispatched")
 2  T1    Customer calls support: "I changed my mind"
 3  T2    Support clicks Force cancel -> SupportController.forceCancel
 4  T3    status is "dispatched" -> not "cancelled" -> refund triggered, status = "cancelled"
 5  T4    Fulfilment's carrier delivers the parcel on T+2
 6  T5    Month end: stock and money no longer match
 customer service layer saw the rule; the support tool did not

Real scenario: An audit query (measuring) finds orders that went from dispatched to cancelled; the cause is two call sites, not one.

Fix / how to use it: Solving the classic problems and the Go test TestAnemicDrift_SupportCancelsDispatchedOrder, which passes and documents the hole.

The costs of forced richness in a simple domain Important ​

In plain words: A rich model for a note-taking screen is a vault door on a shoebox. It protects nothing and slows everyone down.

Common misunderstanding: "If we do DDD, everything must be an aggregate." Evans separates a core domain, where the model is worth the effort, from supporting and generic areas. DDD spends effort where the business wins or loses.

Definition: Forced richness means building aggregates, mappers, events and handlers for an area that has no invariant worth protecting. It adds code and indirection, with nothing to protect in exchange.

CostSymptomCheaper design
CeremonySix files to save a noteOne function and a struct (simple/note.go)
Mapper taxDomain object, record object, mapper, three testsEloquent model directly
Hidden CRUDOrderNoteFactory, OrderNoteRepository for a text fieldupdateOrCreate in an action
Team slowdownA one-field change touches four layersCollapse layers in supporting areas
False comfort"It is DDD" so nobody questions itSay which pattern each area uses
 forced richness (composite)
 1  Catalog adds "internal product notes"
 2  Developer creates ProductNoteAggregate, ProductNoteFactory, ProductNoteRepository, ProductNoteMapper
 3  Rule enforced: body is not empty
 4  Same rule fits in one line of validation
 5  Result: 140 lines, 4 files, no extra safety

Real scenario: A reference-data screen (countries, tax categories) with a full aggregate; an admin CRUD for FAQ items with domain events nobody consumes.

Fix / how to use it: Strategy 3 in Eloquent and anemia, or a Transaction Script like SaveNote in the Go snippets.

Tell, don't ask, and encapsulation Important ​

In plain words: Do not take an object's data, decide something, and put data back. Tell the object what you want and let it decide.

Common misunderstanding: "Encapsulation means private fields and public getters." Getters for every field give you a bag with a lock icon. Fowler on Tell-Don't-Ask: "rather than asking an object for data and acting on that data, we should instead tell an object what to do."

Definition: Tell-Don't-Ask moves a decision to the object that owns the data. Encapsulation hides the state so the object, not the caller, preserves the invariants. Related smells from Code Smells & Refactoring: Feature Envy (a method envies another object's data), Data Class (an object with only data), Primitive Obsession (strings for status), Inappropriate Intimacy; and the Law of Demeter for call chains like order.Customer.Address.Country.

Ask styleTell style
if order.Status != "dispatched" { order.Status = "cancelled" }order.Cancel(reason, now)
total += l.Quantity * l.Price in every serviceorder.Total()
if len(order.Lines) >= 20 { return err } before appendorder.AddLine(...) returns ErrTooManyLines
Read status, compare, write statusorder.MarkPaid(now)
 ask vs tell (Go)
 1  ask    s := order.Status; if s == "dispatched" { return err }; order.Status = "cancelled"
 2  tell   if err := order.Cancel(reason, now); err != nil { return err }
 3  gain   the dispatched rule now has exactly one home

Real scenario: Fowler's alarm monitor: am.setValue(3); if (am.getValue() > am.getLimit()) alarm.warn(...) becomes tm.setValue(3). He adds "personally, I don't use tell-dont-ask" and warns it can breed "GetterEradicators"; he prefers to "co-locate data and behavior". Treat it as a lens, not a law.

Fix / how to use it: Replace each "read, decide, write" block with one method named in the ubiquitous language.

Where does the logic go: entity, domain service or application service Important ​

In plain words: If one object has all the facts, the rule is its method. If a rule needs two aggregates, it is a domain service. If it is a step in a use case, it is an application service.

Common misunderstanding: "Services are the problem." Evans: a service is right "when a significant process or transformation in the domain is not a natural responsibility of an entity or value object". The problem is services that take what belongs to the object.

Definition: Three homes for logic. The deep treatment is in Domain, Application & Infrastructure Services; here is the test.

QuestionIf yesExample in the running domain
Does one object own all the data the rule needs?Method on the entity or aggregateOrder.Cancel
Is the rule about a value?Method on the value objectMoney.Add, Money.Times
Does the rule need two aggregates or an outside policy?Domain serviceShippingCostCalculator(order, carrierRates)
Is it "load, call, save, publish"?Application serviceCancelOrderHandler
Is it a technical concern (HTTP, SQL, mail)?Infrastructure servicePostgresOrderRepository

Clean Architecture says the same in different words: "Entities encapsulate Enterprise wide business rules", and use cases "orchestrate the flow of data to and from the entities, and direct those entities to use their enterprise wide business rules". Fowler adds that the Service Layer "establishes a set of available operations and coordinates the application's response in each operation", and Evans: it "is kept thin".

Real scenario: "Cancel" is on Order; "Choose the cheapest carrier for these orders" is a domain service; "Handle the cancel request" is a handler.

Fix / how to use it: Run the test above in code review: any if over an entity's fields in a service is a candidate to move.

Making illegal states unrepresentable Must-know ​

In plain words: Instead of checking for bad data everywhere, shape the types so bad data cannot be written down.

Common misunderstanding: "Validation is enough." Validation catches bad input at the doors you remembered. An illegal state is a possible value of the type; every door can produce it. Alexis King: "Use a data structure that makes illegal states unrepresentable."

Definition: Use the type system, constructors and a state machine so that invalid values and transitions have no code path.

TechniqueRemovesExample
Closed enum for statusTypos like canceledenum OrderStatus: string in PHP; type Status string with constants in Go
Transition table (state machine)Skipping statesPaid → Dispatched allowed, Dispatched → Cancelled not
Value objectNegative money, mixed currenciesMoney{Minor, Currency} with Add checking currency
Smart constructorHalf-built objectsNewOrder(id, customer, currency)
Derived valuesTwo totals disagreeingTotal() computed from lines
Unexported fields (Go) / private properties (PHP)Direct writesCallers must go through methods
Separate types per phaseOperations on the wrong phaseDraftOrder vs PlacedOrder
Database CHECK, foreign keysBad rows from imports and raw SQLCHECK (quantity BETWEEN 1 AND 50)
 order state machine (the single table in code)
 1  draft      -> placed, cancelled
 2  placed     -> paid, cancelled
 3  paid       -> dispatched, cancelled   (refund due)
 4  dispatched -> (none)                  // "request a return instead"
 5  cancelled  -> (none)

Real scenario: The status = 'canceled' import bug disappears when Restore refuses unknown statuses and the table has a CHECK.

Fix / how to use it: Mechanics shows the SQL and the Go and PHP versions; Entities & Value Objects owns the building blocks.

Eloquent and anemia Must-know ​

In plain words: An Eloquent model is shaped like a table and saves itself. That makes it a data bag by default. You can make it richer, hide it behind a domain object, or accept it for simple areas.

Common misunderstanding: "Eloquent cannot do DDD." Eloquent implements Active Record. Active Record can carry behaviour; what it cannot do is hide its persistence shape. Laravel's own docs describe it this way: "each database table has a corresponding 'Model' that is used to interact with that table."

Definition: Three strategies, from least to most separation.

StrategyWhat it isRules live inPersistenceCosts
1. Rich Eloquent modelActive Record with guarded setters, enum accessor, domain methodsThe modelThe model itself (save() by the action)Cannot stop forceFill, query()->update(), raw SQL; model tied to schema
2. Separate domain object + mapperPlain PHP aggregate; OrderRecord Eloquent model as persistence shapeThe domain objectA repository maps domain to recordsMapper code, two shapes to keep in sync
3. Actions over EloquentOne class per use case; model is data; rules are in validationThe actionEloquentAnemic by choice; right for simple areas only
Criterion1. Rich Eloquent2. Domain object + mapper3. Actions
Setup effortLowHighLowest
Unit test without databaseYes (domain methods do not save)Yes, pure PHPNeeds a database or a fake
Invariant enforcementConvention plus guards; bypassableStrong (private state, no ORM in the model)Only validation
Mapping bugsNonePossibleNone
Query convenienceFull EloquentThrough the repository, plus read modelsFull Eloquent
FitsSupporting with real rules; moderate coreCore aggregatesSimple CRUD, supporting, generic
Migration pathCan move to 2 laterTarget for coreCan grow into 1

Eloquent features you will use (all from the Laravel 13 docs read for this page): #[Fillable] / #[Guarded] attributes and the mass-assignment note "all Eloquent models are protected against mass assignment vulnerabilities by default"; the casts() method with enum casting; Attribute::make(get:, set:) for accessors and mutators; Model::preventSilentlyDiscardingAttributes() to throw when filling an unfillable attribute; DB::transaction and lockForUpdate() for the application step. The "action" class is a community convention (single-invokable use-case classes), not a Laravel feature; Laravel's docs do not define it.

 strategy 1: the bypasses, in order of how often they appear in real code
 1  $order->status = 'cancelled'            -> blocked by the setter that throws
 2  $order->forceFill(['total_minor' => ...]) -> NOT blocked for columns without a guard (forceFill skips the fillable list)
 3  Order::query()->update([...])           -> NOT blocked (no model events, no mutators)
 4  DB::table('orders')->update([...])      -> NOT blocked
 5  raw SQL, import tools                   -> only a CHECK constraint stops these

forceFill skips the fillable list only; a column with its own guarded setter (the status here) still refuses, but every unguarded column such as total_minor or paid_at can be overwritten, so treat it as a bypass in review. Close the rest with an architecture test (forbid ->update( on the model outside the repository) and a database CHECK.

Real scenario: Billing's Invoice as strategy 1 (moderate rules, tied to the table); Sales' Order as strategy 2 (core, many states, events); Catalog notes as strategy 3.

Fix / how to use it: Laravel has all three.

Go and anemia Important ​

In plain words: In Go, a struct with capitalised fields is a data bag: any package can write any field. Lowercase the fields and add methods, and the struct protects itself.

Common misunderstanding: "Go has no encapsulation, so DDD is awkward." Go encapsulates at the package level: an unexported field is invisible outside its package. Combined with a package per bounded context, that is stronger than a private keyword per class. Three Dots Labs: "We also need to put our types in a separate package and make all attributes private."

Definition: The Go moves from anemic to rich:

Anemic GoRich GoWhy
type Order struct { Status string }type Order struct { status Status }Others cannot assign
o := Order{} anywhereNewOrder(...) (*Order, error)Valid by construction
o.Status = "cancelled"o.Cancel(reason, now) errorRule checked
Total int64 storedTotal() derivedOne truth
sqlc struct passed everywhereSnapshot and Restore at the repository edgePersistence shape stays outside
package models with all structspackage sales, package fulfilmentA package per context
Interfaces in the DB packageRepository declared by the consumer (app)Dependency points inward
Returning exported slicesReturn copies or viewsCallers cannot mutate behind the back
 go package layout per context
 1  internal/sales/domain        Order, Money, events, errors   (no imports of database/sql)
 2  internal/sales/app           CancelOrder, PlaceOrder        (depends on domain)
 3  internal/sales/adapters      postgres repository, HTTP handler
 4  internal/fulfilment/...      own Order meaning, own package

Real scenario: Wild Workouts' hour.Hour: private availability, ScheduleTraining() returns ErrHourNotAvailable, tests need "no mocks". Go's internal/ directory prevents other modules from importing a package, adding a second wall.

Fix / how to use it: Go.

Testing differences Important ​

In plain words: A rule inside an object is tested by calling the object. A rule inside a service is tested by building a world around the service.

Common misunderstanding: "More mocks mean more coverage." Mocks test wiring. The rule you care about is a few lines in the middle of many setup lines.

Definition: Test shape follows rule placement.

AspectAnemicRich
Rule testService plus fake repository (or database)The object alone
SetupSeed rows, fakes, mocks of BillingBuild via methods
SpeedMilliseconds to secondsMicroseconds
What breaks the testSchema, mapper, wiringOnly a rule change
Coverage of bypass pathsNeeds a test per callerOne test covers every caller
Test namesTestServiceCancelRefusesDispatched"a dispatched order cannot be cancelled"
Integration testsMany (the rules are in them)Few (mapper and wiring only)
 test pyramid shift
 1  anemic  many integration tests, few unit tests; rules checked through the service and the store
 2  rich    many unit tests on the aggregate; a handful of integration tests for mapper, transaction and locking

Real scenario: In the chapter code before.TestServiceCancelRefusesDispatched needs fakeRepo and fakeBilling; sales.TestCancel needs nothing and has four cases in a table. Three Dots Labs notes the same: "we don't need to mock anything here".

Fix / how to use it: Write the characterization table first (Solving); then add unit tests per rule on the object.

Measuring: where do the invariants live? Good to know ​

In plain words: You can count your way to an answer. How many places know the cancel rule? How many tests need a database to check it?

Common misunderstanding: "Rich model" is a feeling. It is measurable.

Definition: Two direct measures and two indirect ones.

MetricCommand or queryTarget
Rule locationsgrep -rn '"dispatched"' --include='*.go' .One in the domain, one in the schema
Tests needing a storeCount tests that touch a DB, container or repository fake for rule checksZero for rules, few for mapping
Impossible rowsSQL query below, run nightlyZero rows
Setter countgrep -c 'Status = ' outside the packageZero outside the aggregate
sql
-- impossible-state audit: every row here is a bug in some caller
SELECT id, status, total_minor FROM orders
WHERE status NOT IN ('draft','placed','paid','dispatched','cancelled')
   OR (status IN ('paid','dispatched') AND paid_at IS NULL)
   OR total_minor <> COALESCE((SELECT SUM(quantity * unit_minor) FROM order_lines l WHERE l.order_id = orders.id), 0);

-- lines that should never exist
SELECT order_id, sku, quantity FROM order_lines WHERE quantity < 1 OR quantity > 50;

Real scenario: After the refactoring, the grep for "dispatched" returns the constant in sales/order.go and the migration; the audit query returns zero rows; go test ./sales takes about a millisecond.

Fix / how to use it: Put the audit query on a nightly job and the grep in an architecture test.

Mechanics ​

Hydration: how a rich object comes back from the database ​

Important A rich object cannot be built by reflection into private fields without care. Two designs:
DesignHowProCon
Restore(snapshot) / restore(...)A static factory that rebuilds state and re-checks invariantsBroken rows are reportedMust be kept in sync with the constructor rules
Reflection or ORM hydrationThe ORM sets private fieldsNo mapper codeInvalid rows are loaded silently
Eloquent as the hydratorModel::newFromBuilder uses raw attributes (mutators bypassed)Zero codeCannot refuse bad rows
 hydration with checking (Go, sales.Restore)
 1  repo reads row                -> Snapshot{Status: "canceled"}
 2  Restore validates the status  -> unknown status error
 3  handler gets an error         -> logs and alerts; no silent bad object
 4  fix the row or the importer   -> the audit query finds the sibling rows

The bypass paths and how to close them ​

BypassWhereClosed by
Public fieldGo, PHP public propertyUnexport, private property, readonly
Public setterAnyRemove; use a domain verb
$guarded = []Laravel#[Fillable] with a short list; preventSilentlyDiscardingAttributes in local
forceFill, unguardedLaravelArchitecture test; code review
Model::query()->update()LaravelRepository only; architecture test
Raw SQL, importersAnyCHECK constraints, NOT NULL, foreign keys
ReflectionAnyOut of scope; trust boundary is the team
Second implementation of the ruleAnyDelete it; one function

The database as the last wall ​

The model protects against code you wrote; constraints protect against code you did not. Add both (PostgreSQL syntax; MySQL 8.0.16 and later also enforces CHECK, older versions parse and ignore it).

sql
ALTER TABLE orders
  ADD CONSTRAINT orders_status_valid
  CHECK (status IN ('draft','placed','paid','dispatched','cancelled')) NOT VALID;

ALTER TABLE orders VALIDATE CONSTRAINT orders_status_valid;   -- scans existing rows, takes a weaker lock

ALTER TABLE order_lines
  ADD CONSTRAINT lines_quantity_range CHECK (quantity BETWEEN 1 AND 50);

ALTER TABLE orders
  ADD CONSTRAINT orders_paid_has_timestamp
  CHECK (status NOT IN ('paid','dispatched') OR paid_at IS NOT NULL);

NOT VALID makes the constraint apply to new writes immediately and lets you clean old rows before VALIDATE CONSTRAINT; see Schema Design and ACID & Transactions. Concurrent cancels are a separate problem: serialise with a row lock or a version column (Optimistic vs Pessimistic Locking); the aggregate protects invariants inside one transaction, not between two.

Where the transaction boundary sits ​

LayerOwnsDoes not own
Domain objectInvariants within one aggregateTransactions, I/O
Application serviceThe transaction, load and save, event publicationBusiness rules
RepositoryMapping and locking (SELECT ... FOR UPDATE)Rules
OutboxEvents written with the aggregate in the same transactionDelivery (Outbox)

Go ​

The module is docs/snippets/ddd/anemic-vs-rich-models/go; gofmt -l . is clean, and go vet ./... and go test ./... pass. Packages: before (anemic), sales (rich aggregate), app (thin handler), characterize (one table run against both), simple (a case where a script is right).

Before: services and a bag of fields ​

Order has exported fields and a free-string Status; OrderService holds the cancel rule:

go
// Package before is the anemic version of Sales. Order is a bag of exported
// fields; every rule lives in services, so every service must remember every rule.
package before

import (
	"errors"
	"time"
)

// Line is one SKU and a quantity. Anyone may change any field.
type Line struct {
	SKU       string
	Quantity  int
	UnitPrice int64 // minor units
}

// Order has no behaviour. Status is a free string: "draft", "placed", "paid",
// "dispatched", "cancelled"... or anything else a caller assigns.
type Order struct {
	ID           string
	CustomerID   string
	Status       string
	Currency     string
	Lines        []Line
	Total        int64
	PaidAt       *time.Time
	CancelReason string
}

// Repository loads and saves the data bag.
type Repository interface {
	Get(id string) (*Order, error)
	Save(o *Order) error
}

// Refunder asks Billing to return money.
type Refunder interface {
	Refund(orderID string, amount int64) error
}

var (
	ErrNotEditable = errors.New("order is not editable")
	ErrBadQuantity = errors.New("quantity must be between 1 and 50")
	ErrDispatched  = errors.New("order already dispatched")
	ErrCancelled   = errors.New("order already cancelled")
	ErrEmpty       = errors.New("order has no lines")
)

// OrderService is the "service that does things": it reads the bag, applies
// rules in a procedure, and writes the bag back (a Transaction Script).
type OrderService struct {
	Repo    Repository
	Billing Refunder
	Now     func() time.Time
}

// AddLine validates the quantity here, because the struct cannot.
func (s *OrderService) AddLine(id, sku string, qty int, price int64) error {
	o, err := s.Repo.Get(id)
	if err != nil {
		return err
	}
	if o.Status != "draft" {
		return ErrNotEditable
	}
	if qty < 1 || qty > 50 {
		return ErrBadQuantity
	}
	o.Lines = append(o.Lines, Line{SKU: sku, Quantity: qty, UnitPrice: price})
	o.Total += int64(qty) * price
	return s.Repo.Save(o)
}

// Place commits the draft.
func (s *OrderService) Place(id string) error {
	o, err := s.Repo.Get(id)
	if err != nil {
		return err
	}
	if o.Status != "draft" {
		return ErrNotEditable
	}
	if len(o.Lines) == 0 {
		return ErrEmpty
	}
	o.Status = "placed"
	return s.Repo.Save(o)
}

// Pay records a captured payment.
func (s *OrderService) Pay(id string) error {
	o, err := s.Repo.Get(id)
	if err != nil {
		return err
	}
	if o.Status != "placed" {
		return errors.New("order is not awaiting payment")
	}
	now := s.Now()
	o.PaidAt = &now
	o.Status = "paid"
	return s.Repo.Save(o)
}

// Dispatch is called by Fulfilment.
func (s *OrderService) Dispatch(id string) error {
	o, err := s.Repo.Get(id)
	if err != nil {
		return err
	}
	if o.Status != "paid" {
		return errors.New("order cannot be dispatched yet")
	}
	o.Status = "dispatched"
	return s.Repo.Save(o)
}

// Cancel is rule number one of the cancel story, and it lives only here.
func (s *OrderService) Cancel(id, reason string) error {
	o, err := s.Repo.Get(id)
	if err != nil {
		return err
	}
	if o.Status == "dispatched" {
		return ErrDispatched
	}
	if o.Status == "cancelled" {
		return ErrCancelled
	}
	if o.Status == "paid" {
		if err := s.Billing.Refund(o.ID, o.Total); err != nil {
			return err
		}
	}
	o.Status = "cancelled"
	o.CancelReason = reason
	return s.Repo.Save(o)
}

Two later entry points copy the rule badly or not at all:

go
package before

// SupportService is the admin tool written a year later by another team. It
// copies the cancel rule from memory and forgets the dispatched check.
type SupportService struct {
	Repo    Repository
	Billing Refunder
}

// ForceCancel cancels on behalf of a customer on the phone.
func (s *SupportService) ForceCancel(id, reason string) error {
	o, err := s.Repo.Get(id)
	if err != nil {
		return err
	}
	if o.Status == "cancelled" {
		return ErrCancelled
	}
	if o.Status == "paid" || o.Status == "dispatched" {
		if err := s.Billing.Refund(o.ID, o.Total); err != nil {
			return err
		}
	}
	o.Status = "cancelled" // a dispatched parcel is on the road, and now refunded
	o.CancelReason = reason
	return s.Repo.Save(o)
}

// ImportService is a CSV importer. It builds Orders directly from rows, so
// no rule runs at all.
type ImportService struct{ Repo Repository }

// Import trusts the file.
func (s *ImportService) Import(rows []Order) error {
	for i := range rows {
		if err := s.Repo.Save(&rows[i]); err != nil {
			return err
		}
	}
	return nil
}

The tests pass, and two of them document the holes:

go
package before

import (
	"errors"
	"testing"
	"time"
)

// fakeRepo exists only because every service test needs a store: the rules
// cannot be reached without going through the service and the repository.
type fakeRepo struct{ m map[string]*Order }

func (r *fakeRepo) Get(id string) (*Order, error) {
	o, ok := r.m[id]
	if !ok {
		return nil, errors.New("not found")
	}
	c := *o
	c.Lines = append([]Line(nil), o.Lines...)
	return &c, nil
}
func (r *fakeRepo) Save(o *Order) error { c := *o; r.m[o.ID] = &c; return nil }

type fakeBilling struct{ refunds []int64 }

func (b *fakeBilling) Refund(_ string, amount int64) error {
	b.refunds = append(b.refunds, amount)
	return nil
}

func TestServiceCancelRefusesDispatched(t *testing.T) {
	repo := &fakeRepo{m: map[string]*Order{"o1": {ID: "o1", Status: "dispatched"}}}
	svc := &OrderService{Repo: repo, Billing: &fakeBilling{}, Now: time.Now}
	if err := svc.Cancel("o1", "changed mind"); !errors.Is(err, ErrDispatched) {
		t.Fatalf("want ErrDispatched, got %v", err)
	}
}

// The next two tests PASS. They document the hole: the rule exists in one
// service and is absent in another, and the struct accepts impossible data.
func TestAnemicDrift_SupportCancelsDispatchedOrder(t *testing.T) {
	repo := &fakeRepo{m: map[string]*Order{"o1": {ID: "o1", Status: "dispatched", Total: 5000}}}
	bill := &fakeBilling{}
	sup := &SupportService{Repo: repo, Billing: bill}
	if err := sup.ForceCancel("o1", "phone call"); err != nil {
		t.Fatal(err)
	}
	got, _ := repo.Get("o1")
	if got.Status != "cancelled" || len(bill.refunds) != 1 {
		t.Fatalf("expected the drifted rule to cancel and refund, got %+v", got)
	}
}

func TestAnemicIllegalStatesAreRepresentable(t *testing.T) {
	repo := &fakeRepo{m: map[string]*Order{}}
	bad := []Order{
		{ID: "x1", Status: "canceled"},                                    // spelling drift
		{ID: "x2", Status: "paid", Lines: nil},                            // paid, no lines
		{ID: "x3", Status: "placed", Lines: []Line{{"A", -3, 100}}},       // negative quantity
		{ID: "x4", Status: "dispatched", PaidAt: nil, Total: 9000},        // dispatched, never paid
		{ID: "x5", Status: "draft", Total: 7, Lines: []Line{{"A", 1, 1}}}, // total disagrees with lines
	}
	if err := (&ImportService{Repo: repo}).Import(bad); err != nil {
		t.Fatal(err)
	}
	if len(repo.m) != len(bad) {
		t.Fatalf("every impossible order was accepted: %d of %d", len(repo.m), len(bad))
	}
}

After: the aggregate ​

Status is a closed type, fields are unexported, next is the state machine, Total() is derived, Restore rejects broken rows, and Cancel records an OrderCancelled event with RefundDue:

go
// Package sales is the rich version: Order owns its data and its rules.
// Fields are unexported, so the only way to change state is a method that
// checks the rule first.
package sales

import (
	"errors"
	"fmt"
	"time"
)

type (
	// OrderID identifies an Order inside Sales.
	OrderID string
	// CustomerID references the Customer by identity.
	CustomerID string
	// SKU references a Catalog product by identity.
	SKU string
)

// Status is the Order state machine. The type is closed: only the constants
// below are produced by this package.
type Status string

const (
	Draft      Status = "draft"
	Placed     Status = "placed"
	Paid       Status = "paid"
	Dispatched Status = "dispatched"
	Cancelled  Status = "cancelled"
)

// Invariants owned by the root.
const (
	MaxLines           = 20
	MaxQuantityPerLine = 50
)

// Errors are sentences a support agent can read to a customer.
var (
	ErrNotEditable      = errors.New("only a draft order can be edited")
	ErrBadQuantity      = fmt.Errorf("quantity must be between 1 and %d", MaxQuantityPerLine)
	ErrTooManyLines     = fmt.Errorf("an order holds at most %d lines", MaxLines)
	ErrCurrencyMismatch = errors.New("all lines must use the order currency")
	ErrEmptyOrder       = errors.New("an order needs at least one line")
	ErrBadTransition    = errors.New("this status change is not allowed")
	ErrAlreadyDispatch  = errors.New("the order is already dispatched; request a return instead")
	ErrAlreadyCancelled = errors.New("the order is already cancelled")
)

// Money is a value object: minor units plus an ISO 4217 currency.
type Money struct {
	Minor    int64
	Currency string
}

type line struct {
	sku       SKU
	quantity  int
	unitPrice Money
}

// Order is the aggregate root.
type Order struct {
	id       OrderID
	customer CustomerID
	currency string
	status   Status
	lines    []line
	paidAt   *time.Time
	reason   string
	events   []Event
}

// NewOrder starts a draft. The invalid Order (no id, no currency) cannot be built.
func NewOrder(id OrderID, customer CustomerID, currency string) (*Order, error) {
	if id == "" || customer == "" || len(currency) != 3 {
		return nil, errors.New("an order needs an id, a customer and a 3-letter currency")
	}
	return &Order{id: id, customer: customer, currency: currency, status: Draft}, nil
}

// next is the state machine: the single table of allowed moves.
var next = map[Status][]Status{
	Draft:      {Placed, Cancelled},
	Placed:     {Paid, Cancelled},
	Paid:       {Dispatched, Cancelled},
	Dispatched: {},
	Cancelled:  {},
}

func (o *Order) moveTo(to Status) error {
	for _, s := range next[o.status] {
		if s == to {
			o.status = to
			return nil
		}
	}
	return ErrBadTransition
}

// AddLine adds or merges a line while the order is a draft.
func (o *Order) AddLine(sku SKU, qty int, price Money) error {
	if o.status != Draft {
		return ErrNotEditable
	}
	if price.Currency != o.currency {
		return ErrCurrencyMismatch
	}
	for i := range o.lines {
		if o.lines[i].sku == sku {
			if merged := o.lines[i].quantity + qty; qty >= 1 && merged <= MaxQuantityPerLine {
				o.lines[i].quantity = merged
				return nil
			}
			return ErrBadQuantity
		}
	}
	if qty < 1 || qty > MaxQuantityPerLine {
		return ErrBadQuantity
	}
	if len(o.lines) >= MaxLines {
		return ErrTooManyLines
	}
	o.lines = append(o.lines, line{sku: sku, quantity: qty, unitPrice: price})
	return nil
}

// Total is derived, never stored, so it cannot disagree with the lines.
func (o *Order) Total() Money {
	t := Money{Currency: o.currency}
	for _, l := range o.lines {
		t.Minor += int64(l.quantity) * l.unitPrice.Minor
	}
	return t
}

// Place commits the draft and records OrderPlaced.
func (o *Order) Place(now time.Time) error {
	if len(o.lines) == 0 {
		return ErrEmptyOrder
	}
	if err := o.moveTo(Placed); err != nil {
		return err
	}
	o.record(OrderPlaced{OrderID: o.id, Total: o.Total(), At: now})
	return nil
}

// MarkPaid is called when Billing reports the payment captured.
func (o *Order) MarkPaid(now time.Time) error {
	if err := o.moveTo(Paid); err != nil {
		return err
	}
	o.paidAt = &now
	return nil
}

// Dispatch is called when Fulfilment hands the parcel to the carrier.
func (o *Order) Dispatch(now time.Time) error {
	if err := o.moveTo(Dispatched); err != nil {
		return err
	}
	o.record(OrderDispatched{OrderID: o.id, At: now})
	return nil
}

// Cancel withdraws the commitment. The rule "a dispatched order cannot be
// cancelled" lives here once; every caller (customer, support, import) goes
// through it. A paid order records that a refund is due; Billing reacts to it.
func (o *Order) Cancel(reason string, now time.Time) error {
	switch o.status {
	case Dispatched:
		return ErrAlreadyDispatch
	case Cancelled:
		return ErrAlreadyCancelled
	}
	refundDue := o.status == Paid
	if err := o.moveTo(Cancelled); err != nil {
		return err
	}
	o.reason = reason
	o.record(OrderCancelled{OrderID: o.id, Reason: reason, RefundDue: refundDue, Refund: o.Total(), At: now})
	return nil
}

// Status reads the state; there is no setter.
func (o *Order) Status() Status { return o.status }

// ID reads the identity.
func (o *Order) ID() OrderID { return o.id }

// PullEvents hands the recorded events to the application service once.
func (o *Order) PullEvents() []Event {
	ev := o.events
	o.events = nil
	return ev
}

func (o *Order) record(e Event) { o.events = append(o.events, e) }

// Snapshot is the persistence shape. Repositories map it to rows.
type Snapshot struct {
	ID         string
	CustomerID string
	Currency   string
	Status     string
	PaidAt     *time.Time
	Reason     string
	Lines      []LineSnapshot
}

// LineSnapshot is one row of the lines table.
type LineSnapshot struct {
	SKU       string
	Quantity  int
	UnitMinor int64
}

// Snapshot exports the state for storage.
func (o *Order) Snapshot() Snapshot {
	s := Snapshot{ID: string(o.id), CustomerID: string(o.customer), Currency: o.currency,
		Status: string(o.status), PaidAt: o.paidAt, Reason: o.reason}
	for _, l := range o.lines {
		s.Lines = append(s.Lines, LineSnapshot{SKU: string(l.sku), Quantity: l.quantity, UnitMinor: l.unitPrice.Minor})
	}
	return s
}

// Restore rebuilds an Order from storage. It re-checks the data: a row that
// breaks an invariant is reported, not silently loaded.
func Restore(s Snapshot) (*Order, error) {
	o, err := NewOrder(OrderID(s.ID), CustomerID(s.CustomerID), s.Currency)
	if err != nil {
		return nil, err
	}
	st := Status(s.Status)
	if _, ok := next[st]; !ok {
		return nil, fmt.Errorf("unknown status %q in storage", s.Status)
	}
	for _, l := range s.Lines {
		if l.Quantity < 1 || l.Quantity > MaxQuantityPerLine {
			return nil, ErrBadQuantity
		}
		o.lines = append(o.lines, line{SKU(l.SKU), l.Quantity, Money{l.UnitMinor, s.Currency}})
	}
	if len(o.lines) > MaxLines {
		return nil, ErrTooManyLines
	}
	o.status, o.paidAt, o.reason = st, s.PaidAt, s.Reason
	return o, nil
}
go
package sales

import "time"

// Event is something that happened in Sales, named in the past tense.
type Event interface{ EventName() string }

// OrderPlaced: the customer committed to buy.
type OrderPlaced struct {
	OrderID OrderID
	Total   Money
	At      time.Time
}

// EventName implements Event: the class name, not the wire type.
func (OrderPlaced) EventName() string { return "OrderPlaced" }

// OrderDispatched: the parcel left the warehouse.
type OrderDispatched struct {
	OrderID OrderID
	At      time.Time
}

// EventName implements Event: the class name, not the wire type.
func (OrderDispatched) EventName() string { return "OrderDispatched" }

// OrderCancelled: the commitment was withdrawn. RefundDue tells Billing to act.
type OrderCancelled struct {
	OrderID   OrderID
	Reason    string
	RefundDue bool
	Refund    Money
	At        time.Time
}

// EventName implements Event: the class name, not the wire type.
func (OrderCancelled) EventName() string { return "OrderCancelled" }

The tests need no database, no fake and no mock:

go
package sales

import (
	"errors"
	"testing"
	"time"
)

var t0 = time.Date(2026, 11, 25, 10, 0, 0, 0, time.UTC)

func eur(n int64) Money { return Money{Minor: n, Currency: "EUR"} }

// newOrderAt builds an order in a given state through the public methods only.
func newOrderAt(t *testing.T, target Status) *Order {
	t.Helper()
	o, err := NewOrder("o1", "c1", "EUR")
	if err != nil {
		t.Fatal(err)
	}
	if err := o.AddLine("SKU-1", 2, eur(2500)); err != nil {
		t.Fatal(err)
	}
	if target == Cancelled {
		target = Placed // the test cancels it once itself
	}
	steps := []func(time.Time) error{o.Place, o.MarkPaid, o.Dispatch}
	order := []Status{Placed, Paid, Dispatched}
	for i, s := range order {
		if o.status == target {
			break
		}
		if err := steps[i](t0); err != nil {
			t.Fatalf("reaching %s: %v", s, err)
		}
	}
	return o
}

// These tests need no database, no mock and no service: the rule is a method.
func TestCancel(t *testing.T) {
	cases := []struct {
		name      string
		from      Status
		wantErr   error
		wantState Status
		refundDue bool
	}{
		{"a placed order can be cancelled", Placed, nil, Cancelled, false},
		{"a paid order is cancelled and a refund is due", Paid, nil, Cancelled, true},
		{"a dispatched order cannot be cancelled", Dispatched, ErrAlreadyDispatch, Dispatched, false},
		{"a cancelled order cannot be cancelled twice", Cancelled, ErrAlreadyCancelled, Cancelled, false},
	}
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			o := newOrderAt(t, c.from)
			if c.from == Cancelled {
				if err := o.Cancel("first", t0); err != nil {
					t.Fatal(err)
				}
			}
			o.PullEvents()
			err := o.Cancel("changed mind", t0)
			if !errors.Is(err, c.wantErr) {
				t.Fatalf("err = %v, want %v", err, c.wantErr)
			}
			if o.Status() != c.wantState {
				t.Fatalf("status = %s, want %s", o.Status(), c.wantState)
			}
			ev := o.PullEvents()
			if c.wantErr == nil {
				got, ok := ev[0].(OrderCancelled)
				if !ok || got.RefundDue != c.refundDue {
					t.Fatalf("events = %#v", ev)
				}
			} else if len(ev) != 0 {
				t.Fatalf("a rejected command must record nothing, got %#v", ev)
			}
		})
	}
}

func TestInvariants(t *testing.T) {
	o, _ := NewOrder("o1", "c1", "EUR")
	if err := o.AddLine("A", 0, eur(1)); !errors.Is(err, ErrBadQuantity) {
		t.Fatalf("quantity 0: %v", err)
	}
	if err := o.AddLine("A", 1, Money{1, "USD"}); !errors.Is(err, ErrCurrencyMismatch) {
		t.Fatalf("currency: %v", err)
	}
	if err := o.Place(t0); !errors.Is(err, ErrEmptyOrder) {
		t.Fatalf("empty: %v", err)
	}
	if _, err := NewOrder("", "c1", "EUR"); err == nil {
		t.Fatal("an order without id must not exist")
	}
}

func TestTotalIsDerived(t *testing.T) {
	o := newOrderAt(t, Draft)
	_ = o.AddLine("SKU-2", 1, eur(500))
	if got := o.Total(); got.Minor != 5500 {
		t.Fatalf("total = %d", got.Minor)
	}
}

func TestRestoreRejectsImpossibleRows(t *testing.T) {
	bad := []Snapshot{
		{ID: "x1", CustomerID: "c", Currency: "EUR", Status: "canceled"},
		{ID: "x3", CustomerID: "c", Currency: "EUR", Status: "placed", Lines: []LineSnapshot{{"A", -3, 100}}},
	}
	for _, s := range bad {
		if _, err := Restore(s); err == nil {
			t.Fatalf("row %s was accepted", s.ID)
		}
	}
	o := newOrderAt(t, Paid)
	back, err := Restore(o.Snapshot())
	if err != nil || back.Status() != Paid || back.Total() != o.Total() {
		t.Fatalf("round trip failed: %v", err)
	}
}

The application layer shrinks to load, call, save, publish:

go
// Package app is the thin application layer: load, call the aggregate, save,
// publish. It holds no business rule.
package app

import (
	"context"
	"time"

	"academy/anemic-vs-rich-models/sales"
)

// Repository is defined where it is used (the domain/app side), not in the DB package.
type Repository interface {
	Get(ctx context.Context, id sales.OrderID) (*sales.Order, error)
	Save(ctx context.Context, o *sales.Order) error
}

// Publisher stands for the outbox: events are stored with the order, then relayed.
type Publisher interface {
	Publish(ctx context.Context, events []sales.Event) error
}

// CancelOrder is the use case "cancel an order".
type CancelOrder struct {
	Repo Repository
	Pub  Publisher
	Now  func() time.Time
}

// Handle contains no `if status ==`. It only orchestrates.
func (h CancelOrder) Handle(ctx context.Context, id sales.OrderID, reason string) error {
	o, err := h.Repo.Get(ctx, id)
	if err != nil {
		return err
	}
	if err := o.Cancel(reason, h.Now()); err != nil {
		return err
	}
	if err := h.Repo.Save(ctx, o); err != nil {
		return err
	}
	return h.Pub.Publish(ctx, o.PullEvents())
}
go
package app

import (
	"context"
	"errors"
	"testing"
	"time"

	"academy/anemic-vs-rich-models/sales"
)

type memRepo struct {
	m map[sales.OrderID]sales.Snapshot
}

func (r *memRepo) Get(_ context.Context, id sales.OrderID) (*sales.Order, error) {
	s, ok := r.m[id]
	if !ok {
		return nil, errors.New("not found")
	}
	return sales.Restore(s)
}

func (r *memRepo) Save(_ context.Context, o *sales.Order) error {
	r.m[o.ID()] = o.Snapshot()
	return nil
}

type memPub struct{ got []sales.Event }

func (p *memPub) Publish(_ context.Context, ev []sales.Event) error {
	p.got = append(p.got, ev...)
	return nil
}

func TestCancelOrderUseCase(t *testing.T) {
	now := time.Date(2026, 11, 25, 10, 0, 0, 0, time.UTC)
	o, _ := sales.NewOrder("o1", "c1", "EUR")
	_ = o.AddLine("SKU-1", 1, sales.Money{Minor: 1000, Currency: "EUR"})
	_ = o.Place(now)
	_ = o.MarkPaid(now)
	repo := &memRepo{m: map[sales.OrderID]sales.Snapshot{"o1": o.Snapshot()}}
	pub := &memPub{}
	h := CancelOrder{Repo: repo, Pub: pub, Now: func() time.Time { return now }}

	if err := h.Handle(context.Background(), "o1", "changed mind"); err != nil {
		t.Fatal(err)
	}
	if repo.m["o1"].Status != "cancelled" {
		t.Fatalf("stored status = %s", repo.m["o1"].Status)
	}
	ev, ok := pub.got[0].(sales.OrderCancelled)
	if !ok || !ev.RefundDue {
		t.Fatalf("events = %#v", pub.got)
	}
	if err := h.Handle(context.Background(), "o1", "again"); !errors.Is(err, sales.ErrAlreadyCancelled) {
		t.Fatalf("second cancel: %v", err)
	}
}

The characterization table: one table, two implementations ​

This is the safety net of the refactoring. A Driver interface hides how each implementation is wired; the nine scenarios run against the anemic service and the rich aggregate, and both must pass with identical outcomes:

go
// Package characterize holds ONE table of scenarios and runs it against the
// anemic service and the rich aggregate. While the table passes for both, the
// refactoring has not changed behaviour.
package characterize

import (
	"context"
	"errors"
	"testing"
	"time"

	"academy/anemic-vs-rich-models/app"
	"academy/anemic-vs-rich-models/before"
	"academy/anemic-vs-rich-models/sales"
)

// Driver is the seam: a scenario speaks only these verbs and a status string.
type Driver interface {
	Do(step string) error
	Status() string
}

var now = time.Date(2026, 11, 25, 10, 0, 0, 0, time.UTC)

// --- adapter 1: the anemic service ------------------------------------------

type memRepo struct{ o *before.Order }

func (r *memRepo) Get(string) (*before.Order, error) { c := *r.o; return &c, nil }
func (r *memRepo) Save(o *before.Order) error        { c := *o; r.o = &c; return nil }

type noRefund struct{}

func (noRefund) Refund(string, int64) error { return nil }

type anemic struct {
	svc  *before.OrderService
	repo *memRepo
}

func newAnemic() Driver {
	repo := &memRepo{o: &before.Order{ID: "o1", Status: "draft", Currency: "EUR"}}
	return &anemic{repo: repo, svc: &before.OrderService{Repo: repo, Billing: noRefund{}, Now: func() time.Time { return now }}}
}

func (a *anemic) Do(step string) error {
	switch step {
	case "add":
		return a.svc.AddLine("o1", "SKU-1", 2, 2500)
	case "add-zero":
		return a.svc.AddLine("o1", "SKU-1", 0, 2500)
	case "place":
		return a.svc.Place("o1")
	case "pay":
		return a.svc.Pay("o1")
	case "dispatch":
		return a.svc.Dispatch("o1")
	case "cancel":
		return a.svc.Cancel("o1", "changed mind")
	}
	return errors.New("unknown step " + step)
}
func (a *anemic) Status() string { return a.repo.o.Status }

// --- adapter 2: the rich aggregate through the thin use case ------------------

type richRepo struct{ s sales.Snapshot }

func (r *richRepo) Get(context.Context, sales.OrderID) (*sales.Order, error) {
	return sales.Restore(r.s)
}
func (r *richRepo) Save(_ context.Context, o *sales.Order) error { r.s = o.Snapshot(); return nil }

type nopPub struct{}

func (nopPub) Publish(context.Context, []sales.Event) error { return nil }

type rich struct {
	repo *richRepo
	h    app.CancelOrder
}

func newRich() Driver {
	o, _ := sales.NewOrder("o1", "c1", "EUR")
	repo := &richRepo{s: o.Snapshot()}
	return &rich{repo: repo, h: app.CancelOrder{Repo: repo, Pub: nopPub{}, Now: func() time.Time { return now }}}
}

// edit loads, mutates through the aggregate's methods and saves.
func (r *rich) edit(f func(*sales.Order) error) error {
	o, err := r.repo.Get(context.Background(), "o1")
	if err != nil {
		return err
	}
	if err := f(o); err != nil {
		return err
	}
	return r.repo.Save(context.Background(), o)
}

func (r *rich) Do(step string) error {
	switch step {
	case "add":
		return r.edit(func(o *sales.Order) error { return o.AddLine("SKU-1", 2, sales.Money{Minor: 2500, Currency: "EUR"}) })
	case "add-zero":
		return r.edit(func(o *sales.Order) error { return o.AddLine("SKU-1", 0, sales.Money{Minor: 2500, Currency: "EUR"}) })
	case "place":
		return r.edit(func(o *sales.Order) error { return o.Place(now) })
	case "pay":
		return r.edit(func(o *sales.Order) error { return o.MarkPaid(now) })
	case "dispatch":
		return r.edit(func(o *sales.Order) error { return o.Dispatch(now) })
	case "cancel":
		return r.h.Handle(context.Background(), "o1", "changed mind")
	}
	return errors.New("unknown step " + step)
}
func (r *rich) Status() string { return r.repo.s.Status }

// --- the shared table -------------------------------------------------------

var scenarios = []struct {
	name       string
	steps      []string
	wantStatus string
	wantFail   bool // the LAST step must be rejected
}{
	{"draft with a line can be placed", []string{"add", "place"}, "placed", false},
	{"an empty draft cannot be placed", []string{"place"}, "draft", true},
	{"zero quantity is rejected", []string{"add-zero"}, "draft", true},
	{"a placed order can be cancelled", []string{"add", "place", "cancel"}, "cancelled", false},
	{"a paid order can be cancelled", []string{"add", "place", "pay", "cancel"}, "cancelled", false},
	{"a dispatched order cannot be cancelled", []string{"add", "place", "pay", "dispatch", "cancel"}, "dispatched", true},
	{"a cancelled order cannot be cancelled twice", []string{"add", "place", "cancel", "cancel"}, "cancelled", true},
	{"an unpaid order cannot be dispatched", []string{"add", "place", "dispatch"}, "placed", true},
	{"a placed order cannot be edited", []string{"add", "place", "add"}, "placed", true},
}

func TestBothImplementationsBehaveTheSame(t *testing.T) {
	impls := map[string]func() Driver{"anemic": newAnemic, "rich": newRich}
	for name, mk := range impls {
		for _, sc := range scenarios {
			t.Run(name+"/"+sc.name, func(t *testing.T) {
				d := mk()
				var err error
				for _, step := range sc.steps {
					err = d.Do(step)
				}
				if (err != nil) != sc.wantFail {
					t.Fatalf("last step error = %v, wantFail = %v", err, sc.wantFail)
				}
				if d.Status() != sc.wantStatus {
					t.Fatalf("status = %s, want %s", d.Status(), sc.wantStatus)
				}
			})
		}
	}
}

A case where anemia is right ​

Catalog's internal product notes are a supporting subdomain with one trivial rule. A struct and a ten-line script is the honest design:

go
// Package simple shows an area where anemia is the right call: Catalog's
// "internal product notes" (a supporting subdomain). There is no invariant
// worth a type, so a data struct and one transaction script are enough.
package simple

import (
	"context"
	"errors"
	"strings"
)

// Note is plain data on purpose.
type Note struct {
	ID      int64
	SKU     string
	Author  string
	Body    string
	Pinned  bool
	Updated int64
}

// Store is whatever persists notes (database/sql, sqlc, GORM).
type Store interface {
	Save(ctx context.Context, n Note) (Note, error)
}

// SaveNote is a Transaction Script: validate, save, return. About ten lines
// and no behaviour that other code could duplicate or contradict.
func SaveNote(ctx context.Context, st Store, n Note) (Note, error) {
	n.Body = strings.TrimSpace(n.Body)
	if n.SKU == "" || n.Body == "" {
		return Note{}, errors.New("a note needs a SKU and a body")
	}
	return st.Save(ctx, n)
}
go
package simple

import (
	"context"
	"testing"
)

type fake struct{ got Note }

func (f *fake) Save(_ context.Context, n Note) (Note, error) { f.got = n; return n, nil }

func TestSaveNoteTrimsAndSaves(t *testing.T) {
	f := &fake{}
	if _, err := SaveNote(context.Background(), f, Note{SKU: "A", Body: "  fragile  "}); err != nil {
		t.Fatal(err)
	}
	if f.got.Body != "fragile" {
		t.Fatalf("body = %q", f.got.Body)
	}
	if _, err := SaveNote(context.Background(), f, Note{SKU: "A"}); err == nil {
		t.Fatal("empty body accepted")
	}
}

The Go angle ​

Go's encapsulation unit is the package, so the pair "unexported fields + constructor" plus "package per bounded context" replaces getters and setters. Exported fields are fine for DTOs, read models and events (they are data on purpose). database/sql, sqlc and GORM structs are persistence shapes: keep them in the adapter and map to the domain through Snapshot and Restore. Interfaces belong to the consumer (the app package declares Repository), which is the same dependency rule as in Repositories. Go has no sum types, so use a named string or int type plus constants plus a transition table; the state machine in sales.next is the substitute. Copy slices on the way out (Snapshot, views), never hand out the internal slice.

Laravel ​

Laravel 13, PHP 8.4. The PHP snippets were reviewed, not run (no PHP on the authoring machine). The Eloquent API calls (#[Fillable], casts(), Attribute::make, lockForUpdate, DB::transaction) were checked against the Laravel 13 docs saved for this page.

Before: anemic Eloquent, a service and a copy ​

An Eloquent model with $guarded = [], a service with the cancel rule, and a support controller with a second copy:

php
<?php

namespace App\Sales;

use App\Billing\RefundGateway;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

// Before: an Eloquent model with no behaviour. Every column is writable from anywhere.
// (Eloquent models are Active Record objects; this one is used as a data bag.)
class Order extends Model
{
    protected $table = 'orders';

    protected $guarded = []; // "just make it work": every attribute is mass assignable
}

// The "service that does things". All rules live here, as a Transaction Script.
final class OrderService
{
    public function __construct(private RefundGateway $billing)
    {
    }

    public function cancel(int $orderId, string $reason): void
    {
        DB::transaction(function () use ($orderId, $reason) {
            $order = Order::query()->lockForUpdate()->findOrFail($orderId);

            if ($order->status === 'dispatched') {
                throw new \DomainException('Order already dispatched.');
            }
            if ($order->status === 'cancelled') {
                throw new \DomainException('Order already cancelled.');
            }
            if ($order->status === 'paid') {
                $this->billing->refund($order->id, $order->total_minor);
            }

            $order->status = 'cancelled';
            $order->cancel_reason = $reason;
            $order->save();
        });
    }
}

// A second entry point, written later by another team, with its own copy of the rule.
final class SupportOrderController
{
    public function forceCancel(Request $request, int $id, RefundGateway $billing): JsonResponse
    {
        $order = Order::findOrFail($id);

        if ($order->status === 'cancelled') {
            return response()->json(['error' => 'already cancelled'], 409);
        }
        if (in_array($order->status, ['paid', 'dispatched'], true)) {
            $billing->refund($order->id, $order->total_minor); // refunds a parcel that is already on the road
        }

        $order->update(['status' => 'cancelled', 'cancel_reason' => $request->string('reason')]);

        return response()->json(['status' => $order->status]);
    }
}

Strategy 1: a rich Eloquent model ​

The OrderStatus enum with its transition table:

php
<?php

namespace App\Sales;

// A closed set of values with the transition table next to it.
enum OrderStatus: string
{
    case Draft = 'draft';
    case Placed = 'placed';
    case Paid = 'paid';
    case Dispatched = 'dispatched';
    case Cancelled = 'cancelled';

    /** @return list<self> */
    public function allowedNext(): array
    {
        return match ($this) {
            self::Draft => [self::Placed, self::Cancelled],
            self::Placed => [self::Paid, self::Cancelled],
            self::Paid => [self::Dispatched, self::Cancelled],
            self::Dispatched, self::Cancelled => [],
        };
    }

    public function canMoveTo(self $to): bool
    {
        return in_array($to, $this->allowedNext(), true);
    }
}

The model: guarded status setter, domain methods that never save, #[Fillable] with only harmless columns:

php
<?php

namespace App\Sales;

use DomainException;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;

// Strategy 1: a rich Eloquent model. It is still Active Record, but the rules are
// methods on it, the status cannot be assigned from outside, and mass assignment
// only covers harmless columns. Domain methods never call save() and never touch
// relations, so they can be unit tested on `new Order()` without a database.
//
// Honest limit: Eloquent cannot fully close the door. `$order->forceFill(...)` on
// unguarded columns, `Order::query()->update(...)` and raw SQL still bypass these methods.
// Code review, an architecture test and a CHECK constraint close the rest.
#[Fillable(['customer_id', 'currency'])]
class Order extends Model
{
    protected $table = 'orders';

    /** The status accessor returns the enum; the setter refuses outside writes. */
    protected function status(): Attribute
    {
        return Attribute::make(
            get: fn (string $value) => OrderStatus::from($value),
            set: fn () => throw new DomainException('Use the domain methods to change the status.'),
        );
    }

    public static function draft(string $customerId, string $currency): self
    {
        $order = new self(['customer_id' => $customerId, 'currency' => $currency]);
        $order->attributes['status'] = OrderStatus::Draft->value;
        $order->attributes['total_minor'] = 0;

        return $order;
    }

    public function cancel(string $reason): void
    {
        $current = $this->status; // OrderStatus via the accessor

        if ($current === OrderStatus::Dispatched) {
            throw new DomainException('The order is already dispatched; request a return instead.');
        }
        if ($current === OrderStatus::Cancelled) {
            throw new DomainException('The order is already cancelled.');
        }

        $this->moveTo(OrderStatus::Cancelled);
        $this->attributes['cancel_reason'] = $reason;
    }

    public function refundDue(): bool
    {
        return $this->paid_at !== null && $this->status === OrderStatus::Cancelled;
    }

    private function moveTo(OrderStatus $to): void
    {
        if (! $this->status->canMoveTo($to)) {
            throw new DomainException("Cannot move from {$this->status->value} to {$to->value}.");
        }
        $this->attributes['status'] = $to->value; // bypasses the guarded setter on purpose
    }
}

The action is the application step (community "action" convention):

php
<?php

namespace App\Sales\Actions;

use App\Sales\Order;
use Illuminate\Support\Facades\DB;

// The application step (community "action" convention, not a Laravel feature):
// one class, one use case, no business rule. It loads, calls the model, saves.
final class CancelOrder
{
    public function __invoke(int $orderId, string $reason): Order
    {
        return DB::transaction(function () use ($orderId, $reason) {
            $order = Order::query()->lockForUpdate()->findOrFail($orderId);

            $order->cancel($reason); // the only place the rule exists

            $order->save();

            return $order;
        });
    }
}

Strategy 2: a pure domain object and a mapper ​

The aggregate has no Laravel imports:

php
<?php

namespace App\Sales\Domain;

use App\Sales\OrderStatus;
use DomainException;
use LogicException;

// Strategy 2: a plain PHP aggregate. No Eloquent, no framework, no database.
// Persistence is a mapper's problem (see EloquentOrderRepository).
final class Order
{
    /** @var list<object> */
    private array $events = [];

    /** @param array<string, array{quantity: int, unitMinor: int}> $lines */
    private function __construct(
        private readonly string $id,
        private readonly string $currency,
        private OrderStatus $status,
        private array $lines,
        private ?string $paidAt,
        private ?string $cancelReason,
    ) {
    }

    public static function draft(string $id, string $currency): self
    {
        if ($id === '' || strlen($currency) !== 3) {
            throw new DomainException('An order needs an id and a 3-letter currency.');
        }

        return new self($id, $currency, OrderStatus::Draft, [], null, null);
    }

    /** Rebuild from storage; rows that break an invariant fail loudly. */
    public static function restore(string $id, string $currency, string $status, array $lines, ?string $paidAt, ?string $cancelReason): self
    {
        foreach ($lines as $sku => $line) {
            if ($line['quantity'] < 1 || $line['quantity'] > 50) {
                throw new LogicException("Stored line {$sku} has an impossible quantity.");
            }
        }

        return new self($id, $currency, OrderStatus::from($status), $lines, $paidAt, $cancelReason);
    }

    public function addLine(string $sku, int $quantity, int $unitMinor): void
    {
        if ($this->status !== OrderStatus::Draft) {
            throw new DomainException('Only a draft order can be edited.');
        }
        $merged = ($this->lines[$sku]['quantity'] ?? 0) + $quantity;
        if ($quantity < 1 || $merged > 50) {
            throw new DomainException('Quantity must be between 1 and 50.');
        }
        $this->lines[$sku] = ['quantity' => $merged, 'unitMinor' => $unitMinor];
    }

    public function total(): int
    {
        return array_sum(array_map(fn (array $l) => $l['quantity'] * $l['unitMinor'], $this->lines));
    }

    public function place(): void
    {
        if ($this->lines === []) {
            throw new DomainException('An order needs at least one line.');
        }
        $this->moveTo(OrderStatus::Placed);
    }

    public function markPaid(string $at): void
    {
        $this->moveTo(OrderStatus::Paid);
        $this->paidAt = $at;
    }

    public function cancel(string $reason): void
    {
        if ($this->status === OrderStatus::Dispatched) {
            throw new DomainException('The order is already dispatched; request a return instead.');
        }
        if ($this->status === OrderStatus::Cancelled) {
            throw new DomainException('The order is already cancelled.');
        }
        $refundDue = $this->status === OrderStatus::Paid;
        $this->moveTo(OrderStatus::Cancelled);
        $this->cancelReason = $reason;
        $this->events[] = new OrderCancelled($this->id, $reason, $refundDue, $this->total());
    }

    /** @return list<object> */
    public function pullEvents(): array
    {
        [$events, $this->events] = [$this->events, []];

        return $events;
    }

    public function status(): OrderStatus
    {
        return $this->status;
    }

    /** @return array<string, mixed> state for the mapper */
    public function toState(): array
    {
        return ['id' => $this->id, 'currency' => $this->currency, 'status' => $this->status->value,
            'lines' => $this->lines, 'paid_at' => $this->paidAt, 'cancel_reason' => $this->cancelReason,
            'total_minor' => $this->total()];
    }

    private function moveTo(OrderStatus $to): void
    {
        if (! $this->status->canMoveTo($to)) {
            throw new DomainException("Cannot move from {$this->status->value} to {$to->value}.");
        }
        $this->status = $to;
    }
}

final readonly class OrderCancelled
{
    public function __construct(
        public string $orderId,
        public string $reason,
        public bool $refundDue,
        public int $refundMinor,
    ) {
    }
}

The repository is the only place that knows OrderRecord and the tables:

php
<?php

namespace App\Sales\Infrastructure;

use App\Sales\Domain\Order;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

// The Eloquent model is now only the persistence shape (rows and columns).
// It carries no rule; the domain object carries all of them.
class OrderRecord extends Model
{
    protected $table = 'orders';
    public $incrementing = false;
    protected $keyType = 'string';
    protected $guarded = [];
}

class OrderLineRecord extends Model
{
    protected $table = 'order_lines';
    public $timestamps = false;
    protected $guarded = [];
}

final class EloquentOrderRepository
{
    public function get(string $id): Order
    {
        $row = OrderRecord::query()->lockForUpdate()->findOrFail($id);
        $lines = OrderLineRecord::query()->where('order_id', $id)->get()
            ->mapWithKeys(fn ($l) => [$l->sku => ['quantity' => $l->quantity, 'unitMinor' => $l->unit_minor]])
            ->all();

        return Order::restore($row->id, $row->currency, $row->status, $lines, $row->paid_at, $row->cancel_reason);
    }

    public function save(Order $order): void
    {
        $s = $order->toState();

        DB::transaction(function () use ($s) {
            OrderRecord::query()->updateOrCreate(['id' => $s['id']], [
                'currency' => $s['currency'], 'status' => $s['status'], 'total_minor' => $s['total_minor'],
                'paid_at' => $s['paid_at'], 'cancel_reason' => $s['cancel_reason'],
            ]);
            OrderLineRecord::query()->where('order_id', $s['id'])->delete();
            foreach ($s['lines'] as $sku => $l) {
                OrderLineRecord::query()->create(['order_id' => $s['id'], 'sku' => $sku,
                    'quantity' => $l['quantity'], 'unit_minor' => $l['unitMinor']]);
            }
        });
    }
}

The handler is thin:

php
<?php

namespace App\Sales\Application;

use App\Sales\Infrastructure\EloquentOrderRepository;
use Illuminate\Support\Facades\DB;

// Strategy 2 application step: a thin handler around the pure aggregate.
final class CancelOrderHandler
{
    public function __construct(private EloquentOrderRepository $orders)
    {
    }

    public function handle(string $orderId, string $reason): void
    {
        DB::transaction(function () use ($orderId, $reason) {
            $order = $this->orders->get($orderId);   // SELECT ... FOR UPDATE inside the repository
            $order->cancel($reason);
            $this->orders->save($order);
            // $order->pullEvents() go to the outbox table in this same transaction
        });
    }
}

Strategy 3: an action for a simple area ​

php
<?php

namespace App\Catalog\Actions;

use App\Catalog\ProductNote;

// Strategy 3: an action over Eloquent for a simple, supporting area.
// No aggregate, no domain object: the rule fits in the validation.
final class SaveProductNote
{
    public function __invoke(string $sku, string $body): ProductNote
    {
        $body = trim($body);
        if ($sku === '' || $body === '') {
            throw new \InvalidArgumentException('A note needs a SKU and a body.');
        }

        return ProductNote::query()->updateOrCreate(['sku' => $sku], ['body' => $body]);
    }
}

Tests (Pest) ​

php
<?php

use App\Sales\Domain\Order;
use App\Sales\Domain\OrderCancelled;
use App\Sales\OrderStatus;
use App\Sales\Order as RichEloquentOrder;

// Pure unit tests: no database, no container, no RefreshDatabase.
function paidOrder(): Order
{
    $order = Order::draft('o1', 'EUR');
    $order->addLine('SKU-1', 2, 2500);
    $order->place();
    $order->markPaid('2026-11-25T10:00:00Z');

    return $order;
}

it('cancels a paid order and records that a refund is due', function () {
    $order = paidOrder();

    $order->cancel('changed mind');

    expect($order->status())->toBe(OrderStatus::Cancelled);
    $events = $order->pullEvents();
    expect($events[0])->toBeInstanceOf(OrderCancelled::class)
        ->and($events[0]->refundDue)->toBeTrue()
        ->and($events[0]->refundMinor)->toBe(5000);
});

it('refuses to cancel a dispatched order', function () {
    $order = Order::restore('o1', 'EUR', 'dispatched', ['SKU-1' => ['quantity' => 1, 'unitMinor' => 100]], null, null);

    expect(fn () => $order->cancel('late'))->toThrow(DomainException::class, 'already dispatched');
});

it('cannot be loaded from an impossible row', function () {
    expect(fn () => Order::restore('x', 'EUR', 'canceled', [], null, null))->toThrow(ValueError::class)
        ->and(fn () => Order::restore('x', 'EUR', 'placed', ['A' => ['quantity' => -3, 'unitMinor' => 1]], null, null))
        ->toThrow(LogicException::class);
});

// Strategy 1 model: still no database, because the domain methods never save.
it('guards the status of the rich Eloquent model', function () {
    $order = RichEloquentOrder::draft('c1', 'EUR');

    expect(fn () => $order->status = 'cancelled')->toThrow(DomainException::class);

    $order->cancel('changed mind');
    expect($order->status)->toBe(OrderStatus::Cancelled);
});

The Laravel angle ​

Eloquent is Active Record: the model is a row with a save(). Make it rich with a closed enum (casts() or an accessor), an Attribute setter that refuses direct status writes, #[Fillable] with a short list, and domain methods that change $this->attributes only. Switch on Model::preventSilentlyDiscardingAttributes(! $this->app->isProduction()) so a stray create(['status' => ...]) throws in development. Keep save(), DB::transaction and lockForUpdate() in the action. If the core rules outgrow the table shape, move to strategy 2 and let an OrderRecord model be the persistence shape (and see ORM Pitfalls for the loading costs). php artisan make:model gives you strategy 3 by default; that is correct for supporting areas and a smell for the Sales core.

Solving the classic problems ​

Refactoring from anemic to rich, step by step ​

Anemic: rules copied per callerRich: one rule, one placeCustomer controllerSupport controllerCSV importOrderService.Cancelchecks dispatchedcopy of the ruleforgot dispatchedno rule at allwrites Status directlyOrder (data bag)exported fieldssame threecallers callCancelOrderHandlerload, call,save, publishOrder.Cancel()rule checked oncefields unexportedeventsthe dispatched parcel can still be refundedevery caller gets the same answerAnemic to rich, six small steps1 Pincharacterizationtable againstthe service2 Extractrule intoOrder.Cancel()service calls it3 Closeunexport fields,add constructor,Restore()4 Typestatus enum +transition table,derived total5 Stranglecallers use thehandler, deletecopied rules6 GuardCHECK constraint,nightly query forimpossible rowsthe characterization table stays green after every stepeach step is its own commit, deployable on its own
StepActionSafety netDone when
1 PinWrite the characterization table against the existing service (characterize test)The table itselfTable is green for the old code
2 ExtractAdd Order.Cancel (a method) and make the service call itTable stays greenThe service has no if status for cancel
3 CloseUnexport fields, add NewOrder and Restore, move construction into itCompiler errors list every callerNo package outside sales assigns a field
4 TypeReplace string Status with the closed type and the next table; derive Total()Table plus Restore testsgrep '"dispatched"' matches once
5 StranglePoint controllers, support tool and importer at the handler; delete copiesTable runs against the handlerSupportService, ImportService rules deleted
6 GuardAdd CHECK constraints, run the impossible-rows query nightlyQuery returns zero rowsThe constraints are validated
 strangling the service (Go, same table, two drivers)
 1  newAnemic()  -> OrderService.Cancel          // old path, table green
 2  newRich()    -> CancelOrder.Handle -> Order.Cancel   // new path, table green
 3  both pass     -> switch the controller to the handler
 4  delete         -> OrderService.Cancel, SupportService.ForceCancel
 5  the table remains as the regression suite
ProblemSolutionHowAdvantageCost
Rule copied in many callersOne method on the aggregateExtract, then point callers to itOne truthCallers must change
Fear of breaking behaviourCharacterization tableSame table, two driversProves equivalenceNeeds writing first
Public fields everywhereUnexport and add constructorFix compile errorsCompiler finds callersChurn
Free-text statusClosed type, transition table, CHECKEnum plus SQLTypos impossibleMigration for old rows
Stored derived value (Total)Compute itMethodNo driftRecompute cost (small)
Mapping from ORM structsSnapshot and RestoreAt the repository edgePersistence isolatedMapper code
Big-bang riskOne aggregate at a timeCore firstValue earlyMixed styles for a while
Team resistanceShow the bugRun the audit query on production dataEvidenceNeeds data access

Choosing ​

SituationPatternLaravel strategyGo shapeReason
Generic: login, password reset, email sendingBuy or reuseFortify, Breeze, a mail packageA libraryNot your edge
Supporting: Catalog notes, FAQ, tagsTransaction ScriptStrategy 3 (actions)Struct plus script (simple)Cheapest correct
Supporting with light derived values: invoice linesActive RecordStrategy 1Struct with a few methodsSome structure, little ceremony
Core with real states: Sales Order, Fulfilment ShipmentDomain ModelStrategy 2 (or 1 if rules are modest)Aggregate in a package per contextRules are the product
Core where history is the product: Billing ledgerEvent-sourced Domain ModelStrategy 2 plus an event storeAggregate rebuilt from eventsAudit and time travel
Reporting, dashboardsRead model, not a domain modelQuery builder, viewssqlx structsReads have no invariants (CQRS)
Data import, ETLTransaction Script with validation through the domainAction calling domain methodsLoop calling Restore or constructorsDo not bypass the model
Prototype, throwawayAnythingStrategy 3ScriptDo not over-design
UnsureStart left, move right on painStrategy 3 then 1 then 2Script then aggregateCost follows evidence

Rule of thumb: move one step right when you see the same rule in a second place, or when a bug comes from a rule one caller forgot. Do not move because a book says so.

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

Monolith: one process, one database ​

Everyday example. A Laravel shop where Sales, Fulfilment and Billing share app/ and one PostgreSQL. The Order aggregate sits in App\Sales\Domain, the cancel action loads it with lockForUpdate(), calls cancel, saves in one transaction. The support tool and the importer call the same action. The rule exists once and the CSV import cannot write canceled, because Restore and the CHECK refuse it.

Production example. The same chapter's before code, found in an audit: three entry points, three copies. The refactoring is the six steps above, each its own deployable commit. The anemic version stays in service until the characterization table passes through the handler.

ConcernAnemicRich
One process, many entry pointsEach copies the ruleAll call one method
TransactionsIn servicesIn the application step
TestingIntegration-heavyUnit-heavy

Modular monolith: boundaries between contexts ​

Everyday example. Sales and Fulfilment live in separate modules in one repository, each with its own Order. Sales' Order is a rich aggregate; Fulfilment's Order (a work order) is smaller and stays an Active Record, because its rules are simple. An architecture test forbids Fulfilment from importing App\Sales\Domain. See Modular Monolith.

Production example. A shared database with module-owned tables: sales_orders, fulfilment_work_orders. Billing reacts to OrderCancelled through an in-process event; the RefundDue flag in the event is data the Order computed, so Billing does not read Sales' tables or re-derive the rule.

BoundaryRich model's role
Module public APICommands and events, never entities
Table ownershipOnly the module's repository writes its tables
Cross-module ruleAn event or a domain service, not a shared setter

Microservices: the boundary becomes a network ​

Everyday example. Sales runs as its own service with its own database. POST /orders/{id}/cancellation calls CancelOrderHandler; the service persists the aggregate and the event in one transaction (Outbox); Billing consumes sales.order.cancelled.v1, sees RefundDue: true, issues the refund (Saga).

Production example. Another team wants "cancel with refund" in one call. In an anemic Sales service they write directly into the table through a shared database, and Sales' rule is lost. In the rich service, Sales owns the only write path and the rule travels with it. See Service Boundaries and Data Ownership.

 cancel across services (rich model)
 1  client            -> POST /orders/1042/cancellation
 2  Sales handler     -> Order.Cancel() ; INSERT outbox(OrderCancelled{RefundDue:true})   // one transaction
 3  relay             -> broker: sales.order.cancelled.v1
 4  Billing consumer  -> idempotent refund for 1042   (inbox, [Idempotent Consumer](/messaging/idempotent-consumer-inbox))
 5  Fulfilment        -> stops picking if not yet dispatched
QuestionAnemic Sales serviceRich Sales service
Who can change statusAnyone with DB access or an update APIOnly the aggregate through the handler
What the event saysOrderUpdated, consumers re-derive meaningOrderCancelled{RefundDue}
Contract stabilityTable shape leaksCommands and events only

Distributed data: replicas, caches, multi-region ​

Everyday example. A read replica serves the order page. The page shows "dispatched" 200 ms late; the cancel button is visible but the command is still checked on the primary by the aggregate, which refuses it. The rule being in the object means a stale UI cannot cause a wrong write.

Production example. A cache of "orders per customer" keeps showing cancelled orders as active for 60 seconds. Because reads are separate from the model, the cache is a read model with its own TTL; it never feeds a decision inside Cancel. When two nodes handle cancel and dispatch at the same time, a version column or lockForUpdate() serialises them (Optimistic vs Pessimistic Locking).

Distributed factEffect on the model
Replica lagNever load the aggregate from a replica for a command
CacheRead models only; invalidate on events
Multi-regionOne writer region per aggregate; commands go to it
Eventual consistency between contextsEvents carry the facts others need

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

LoadWhat changes in this topic
1×Anemic is fine for one entry point and a handful of rules; start with scripts
10×Second and third entry points appear; extract the rule into the aggregate; add CHECK constraints
100×Contention on hot aggregates: keep aggregates small (Aggregates & Factories), version columns, outbox, read models for lists; events replace cross-context reads

Lab: refactor the cancel rule ​

The Go part runs on one machine with no Docker. The database part is described with expected output and marked expected, not run.

 1  cd docs/snippets/ddd/anemic-vs-rich-models/go
 2  go test ./before/ -v
    # expected: TestServiceCancelRefusesDispatched, TestAnemicDrift_SupportCancelsDispatchedOrder,
    #           TestAnemicIllegalStatesAreRepresentable all PASS (the last two document the holes)
 3  go test ./sales/ -v -run TestCancel
    # expected: four sub-tests PASS, no fake, no mock, no store
 4  go test ./characterize/ -v | grep -c PASS
    # expected: 20  (18 sub-tests = 9 scenarios x 2 implementations, the parent test and the final PASS line)
 5  Delete the dispatched check in sales/order.go (comment out the case) and re-run step 4.
    # expected: the rich rows for "a dispatched order cannot be cancelled" fail; the table caught it
 6  grep -rn '"dispatched"' before sales
    # expected: 8 matching lines in 4 files: before/order.go, before/support.go, before/order_test.go and sales/order.go (the constant)

Database part (expected, not run, PostgreSQL):

 7  psql -f orders.sql                            -- create orders and order_lines
 8  INSERT INTO orders (id, status) VALUES ('x1', 'canceled');
    # expected before the CHECK: INSERT 0 1
 9  ALTER TABLE orders ADD CONSTRAINT orders_status_valid CHECK (status IN ('draft','placed','paid','dispatched','cancelled')) NOT VALID;
    # expected: ALTER TABLE; new inserts with 'canceled' now fail:
    # ERROR:  new row for relation "orders" violates check constraint "orders_status_valid"
10  ALTER TABLE orders VALIDATE CONSTRAINT orders_status_valid;
    # expected: ERROR  check constraint "orders_status_valid" of relation "orders" is violated by some row
    #           -> run the impossible-state query from "Measuring", fix 'x1', validate again

Common misconceptions ​

BeliefReality
"Anemic models are always an anti-pattern"Fowler calls them an anti-pattern because they pretend to be a model; for simple areas a Transaction Script is the right design
"A rich model means the entity saves itself"Rich means behaviour on the object; persistence stays behind a repository or a mapper (Active Record is the deliberate exception)
"A service layer means anemic"Fowler's Service Layer is thin and used together with a rich model
"Getters and setters are encapsulation"They expose state; encapsulation protects invariants
"Validation attributes are invariants"They guard the paths that call them; invariants hold for every path
"Eloquent cannot do rich models"It can; it cannot hide the table or stop forceFill, so add constraints and tests
"Functional style is anemic"Immutable data with validating constructors and pure functions can preserve invariants
"DDD means every area gets aggregates"Core areas do; supporting and generic areas should stay simple
"A rich model needs more tests"It needs fewer integration tests and more cheap unit tests
"Moving to rich is a big-bang rewrite"It is six small steps behind a characterization table

Cheat sheet ​

TopicWhat to remember
AnemicData bag plus services holding the rules
RichBehaviour with the data; invariants enforced inside
FowlerAnemic pays model costs, gets no benefits; slips toward Transaction Script
CounterSimple, supporting and generic areas should use scripts or Active Record
SpectrumScript, Active Record, Domain Model, event-sourced; by subdomain and complexity
Tell-Don't-AskMove the decision to the object that owns the data
Where logic goesOne object's rule: object. Two aggregates: domain service. Steps: application service
Illegal statesClosed enum, transition table, value objects, derived values, CHECK
EloquentStrategy 1 rich model, 2 domain object + mapper, 3 actions
GoUnexported fields, constructor, package per context, consumer-side interfaces
TestingRule test with no store; few integration tests
RefactoringPin, extract, close, type, strangle, guard
MeasuringRule locations and tests that need a database
BoundaryRules inside the aggregate; transactions in the application layer; constraints in 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 — State Fowler's objection to anemic models in one sentence and the fair reply. Must-know ​

Answer

Answer: They "incur all of the costs of a domain model, without yielding any of the benefits": you pay for the object mapping and get Transaction Scripts. The fair reply: in simple, supporting or generic areas a script is the right design; the sin is pretending to have a model.

2 — Name the four logic patterns and the subdomain each fits. Good to know ​

Answer

Answer: Transaction Script (simple supporting/generic), Active Record (supporting with light rules), Domain Model (core with complex rules), event-sourced Domain Model (core where history is the value). The mapping is Khononov's heuristic.

3 — Why is if order.Status == "dispatched" in three files a design smell? Must-know ​

Answer

Answer: It is three copies of one rule. Any copy that drifts causes a bug (the refunded parcel). The rule belongs in Order.Cancel.

4 — What does "make illegal states unrepresentable" mean for Status and Total? Must-know ​

Answer

Answer: Use a closed type with a transition table for Status so canceled cannot exist, and derive Total() from lines so two totals cannot disagree. Add a CHECK for the paths outside the code.

5 — Why can the rich Order be unit tested with no store, while the anemic one cannot? Must-know ​

Answer

Answer: The rule is a method on the object, and building an order needs only its constructor and methods. In the anemic design the rule is inside a service that loads and saves through a repository.

6 — List three ways Strategy 1 (rich Eloquent) can be bypassed. Important ​

Answer

Answer: forceFill, Order::query()->update([...]), DB::table('orders')->update(...) or raw SQL. Close them with an architecture test and database CHECK constraints.

7 — In Go, what plays the role of private? Must-know ​

Answer

Answer: Lower-case (unexported) identifiers: they are visible only inside their package. A package per bounded context makes the boundary strong.

8 — What is the first step of the refactoring and why? Important ​

Answer

Answer: Write a characterization table against the existing service. It pins behaviour so each later step can be checked by running the same table on both implementations.

9 — Where do the transaction and the event publication belong? Must-know ​

Answer

Answer: In the application service (handler). The aggregate records events; the handler saves state and events in one transaction (outbox) and publishes after.

10 — Which two numbers measure whether a model is rich? Important ​

Answer

Answer: How many places contain each rule (target: one in the domain plus one CHECK) and how many rule tests need a database or a repository fake (target: none).

Glossary ​

TermOne line
Anemic Domain ModelDomain objects with data and almost no behaviour; rules sit in services
Rich Domain ModelObjects that own their state and enforce invariants through methods
Transaction ScriptOne procedure per request, organising business logic
Table ModuleOne object that handles the logic for all rows of a table
Active RecordAn object wrapping a row, with data access and some domain logic
Domain ModelAn object model that incorporates both behaviour and data
Event-sourced Domain ModelA domain model whose state is the fold of an append-only event stream
Service LayerA thin layer defining the application's operations and coordinating them
Application serviceOrchestrates a use case: load, call, save, publish
Domain serviceStateless operation in the model that fits no single entity
InvariantA rule that must hold after every command
AggregateA consistency boundary with one root that protects its invariants
Tell-Don't-AskTell objects what to do instead of reading their data and deciding
EncapsulationHiding state behind behaviour so the object protects itself
Feature EnvyA method that uses another object's data more than its own
Data ClassAn object with only data and accessors
Primitive ObsessionUsing strings and ints where a domain type belongs
Value ObjectAn immutable object defined by its value (Money)
State machineA table of allowed states and transitions
Smart constructorA constructor that refuses invalid input
MapperCode that converts between domain objects and persistence rows
Snapshot / RestoreA state export for storage and a validating rebuild from it
Characterization testA test that records current behaviour to protect a refactoring
StranglerReplacing an implementation gradually by routing callers to the new one
Mass assignmentFilling many model attributes at once (create, fill)
Fillable / GuardedEloquent allow-list and deny-list for mass assignment
Accessor / MutatorEloquent Attribute::make getters and setters
Enum castEloquent mapping of a column to a PHP backed enum via casts()
CHECK constraintA database rule on a row, enforced for all writers
Read modelA query-shaped copy of data with no invariants
Khononov heuristicPicking the logic pattern by subdomain type and complexity
DDD-liteUsing DDD vocabulary and building blocks without the model's discipline

References ​

  • Martin Fowler, Anemic Domain Model, 25 November 2003. Saved: scratchpad/sources/anemic-vs-rich-models/fowler-anemic.txt
  • Martin Fowler, PoEAA catalog: Transaction Script, Domain Model, Table Module, Service Layer, Active Record. Saved: fowler-transactionscript.txt, fowler-domainmodel.txt, fowler-tablemodule.txt, fowler-servicelayer.txt, fowler-activerecord.txt
  • Martin Fowler, Tell Dont Ask, 5 September 2013. Saved: fowler-telldontask.txt
  • Eric Evans, Domain-Driven Design Reference, 2015: Services, Aggregates. Saved: evans-reference.txt
  • Robert C. Martin, The Clean Architecture, 13 August 2012. Saved: clean-arch.txt
  • Three Dots Labs, Introduction to DDD Lite (Wild Workouts). Saved: threedots-ddd-lite.txt
  • Alexis King, Parse, don't validate, 5 November 2019. Saved: parse-dont-validate.txt
  • Laravel 13, Eloquent and Mutators & Casting. Saved: laravel-eloquent.txt, laravel-mutators.txt
  • Vaughn Vernon, Implementing Domain-Driven Design (2013), ch. 1, and Vlad Khononov, Learning Domain-Driven Design (2021), the logic-pattern heuristic: cited as background, not fetched; no quotes taken, the heuristic is paraphrased and labelled secondary
  • Martin Fowler, Patterns of Enterprise Application Architecture (2002), ch. 9–10: cited through the catalog pages above

Built by Morteza Negahi