Taming Persistence
In this pack:
sizing,
notation,
rule strictness.
Overview
A domain model and a store drift apart unless one object owns the
translation between them. This skill chooses an active record while a
class still mirrors one table row, moves to a data mapper once the
class's fields or rules part from that row, and keeps every mapping
decision at the edge. It also keeps one object per identity within a
transaction, scopes the store's session to one use case, holds lazy
loads inside their aggregate and their transaction, and fills a list
with one read query whose count a test checks.
When to use
- A module is choosing between an active record and a data mapper.
- A domain class extends the mapping tool's base class, carries its
markers, or has a setter that only the mapping tool uses.
- A list screen or a report runs one query for each row it shows.
- Lazily loaded data is touched after the request's session has closed,
or once for each item of a list.
- Two copies of one appointment are loaded in one use case.
- A store session is opened once and kept across requests.
When not to use
- The question is what a repository offers, such as its query methods,
specifications or query objects: that is
designing repositories.
- The question is which objects must change and be stored together in
one transaction: that is
designing aggregates.
- The store holds nothing the domain model rebuilds, such as an
append-only log or a cache of computed figures.
- The question is giving reads a separate model of their own, kept
current from the changes: that is
separating reads from writes,
which builds it as a projection of the changes.
Core rules
Judgement. Choose an active record, an object that is one table
row and saves itself, while a module's classes mirror its tables and
hold few rules, and a data mapper, a separate object that moves data
between domain objects and the store, once a class's fields or rules
part from its table. Placing domain
logic rule 1 decides how a
module organises its logic, and this choice follows it: transaction
scripts sit well on active records, while a domain model needs a
mapper. What tips the balance is whether each class still matches one
table row and holds no rule that spans rows.
Rule. With a data mapper, keep every mapping decision in the
adapter: table and column names, the stored row's shape, and how an
aggregate is rebuilt. Give the mapper nothing the domain would not
give any caller: no public setter and no public constructor added for
it. Where the mapper cannot rebuild through the class's own factory,
as designing repositories
rule 2 asks, map into a separate stored record and convert it in the
adapter, and keep the mapping tool's markers off domain classes, the
way the exception to
inverting dependencies rule
4 keeps a framework's markers off them.
Rule. Within one transaction, answer one object for one identity:
the identity map of the store's session, or the repository itself,
returns the object it already loaded rather than a second copy. An
identity map is the session's record of the object it loaded for each
identity. Two copies of one appointment in one use case each take a
change, and whichever is saved last silently drops the other's.
Rule. Begin and end a unit of work, the session that tracks the
objects it loaded and writes their changes at commit, exactly where
the application service opens and ends the transaction
(placing domain logic rule 2):
one unit of work per use case. A session kept across requests
answers objects other users have since changed, and writes changes
nobody meant to save. Whether changes reach the store by tracking or
by an explicit save stays
designing repositories rule
Rule. Let no lazy load cross an aggregate's boundary or outlive
its transaction: load each aggregate whole (designing
repositories rule 6) and
reach another aggregate by its identity through its own repository
(designing aggregates rule 3).
Lazy loading loads an association when it is first touched, not with
its aggregate, so a lazy reference runs a query at that moment, which
may be in a screen after the session has closed, where it fails, or
once for each item of a list.
Default. Fill a list with one read query that returns the rows it
shows, rather than loading aggregates and touching their
associations one by one, and assert in a test how many queries the
use case runs. A query per row is one read for each item, so the
count grows with the list, and a test that counts queries finds it
before a busy clinic day does. The read query is the one
layering the system rule 6
lets a decision-free read use.
The exception is a list whose length cannot grow, such as one
clinician's breaks in a day: a query per item costs a fixed few.
Pattern
Before, the active record Appointment is one table row that saves
itself, and CompleteAppointment asks it for a status change that
writes the row at once. After, Appointment is a domain object with no
knowledge of its row, Appointments is the port that finds and saves
it, and MappedAppointments keeps the store's session behind that port.
Before:
class Appointment extends StoredRecord
- status: AppointmentStatus
+ static findById(id: AppointmentId): Appointment
+ changeStatus(next: AppointmentStatus): void
status := next
save()
class CompleteAppointment
+ run(id: AppointmentId): void
appointment := Appointment.findById(id)
appointment.changeStatus(Completed)
return
findById is taken to read the row stored under an AppointmentId
and build the appointment, and save() is the message StoredRecord
answers, so changeStatus writes that appointment's row, in the
clinic's database, at once, outside any transaction a use case opened.
AppointmentStatus is the
modeling lifecycles skill's
four-member enumeration, and Completed is one of its members. The
fence shows only the status field, because the row's other columns play
no part here. Any caller can send changeStatus any status, so the
appointment never refuses a move its lifecycle forbids.
After:
class Appointment
- id: AppointmentId
- slot: Slot
- patient: PatientId
- status: AppointmentStatus
- new(id: AppointmentId, slot: Slot, patient: PatientId,
status: AppointmentStatus)
+ static book(id: AppointmentId, slot: Slot,
patient: PatientId): Appointment
slot.reserve(patient)
return new Appointment(id, slot, patient, Scheduled)
+ static restore(id: AppointmentId, slot: Slot, patient: PatientId,
status: AppointmentStatus): Appointment
return new Appointment(id, slot, patient, status)
+ id(): AppointmentId
return id
+ complete(): void
raises AppointmentNotCompletable
if status = InProgress then
status := Completed
else
raise AppointmentNotCompletable
return
interface Appointments
+ find(id: AppointmentId): Appointment
raises AppointmentNotFound
+ save(appointment: Appointment): void
class MappedAppointments implements Appointments
- session: StoreSession
+ new(session: StoreSession)
+ find(id: AppointmentId): Appointment
raises AppointmentNotFound
return session.load(id)
+ save(appointment: Appointment): void
session.store(appointment)
return
class CompleteAppointment
- appointments: Appointments
+ new(appointments: Appointments)
+ run(id: AppointmentId): void
appointment := appointments.find(id)
appointment.complete()
appointments.save(appointment)
return
Appointment keeps the
designing repositories skill's
shape, which adds - id: AppointmentId first, a private constructor
that takes it, book, restore and id(); notation.md's sketch
leaves that field out. complete() is the
modeling lifecycles skill's
transition: it raises AppointmentNotCompletable unless the status is
InProgress, and otherwise sets it to Completed. The appointment
extends nothing.
interface Appointments offers find, which raises
AppointmentNotFound, and save; it leaves out the port's add and
forClinicianOn, which this use case never sends. MappedAppointments
holds a StoreSession set by its constructor: find returns
session.load(id) and save sends session.store(appointment).
CompleteAppointment holds the port set by its constructor and sends
find, complete() and save, once each.
StoredRecord and StoreSession stand for any mapping tool's own
types, and this skill names no mapping tool. session.load(id) is taken
to rebuild the appointment from its row through Appointment.restore,
to answer the same object again for the same identity within the
session, and to raise AppointmentNotFound when no row has that
identity. session.store is taken to write the whole appointment at
commit. What is stored is the completed appointment, under its
AppointmentId, in the clinic's database, in the transaction run
opens, with the session opened and closed with it; the fence leaves
both boundaries out.
Each version changes the status once and stores it once: the Before
version through changeStatus and save(), the After version through
complete() and appointments.save.
Red flags
Places to look, not verdicts. A red flag becomes a finding only with
evidence: a measurement, a reproducible bug, or a failing test.
- A domain class that extends the mapping tool's base class, or carries
its markers.
- A public setter or a public no-argument constructor that exists only
for the mapping tool.
- A list screen or a report whose query count grows with its rows.
- An association loaded on first touch that crosses to another
aggregate.
- A store session kept open across requests or screens.
- Two objects for one identity in one use case.
Common mistakes
- Adopting a data mapper for a module of a few independent rules that
mirror their tables.
- Turning on eager loading everywhere to cure a query per row.
- Letting a template or a view touch an association the use case did
not load.
- Saving an object in the middle of a use case, before its transaction
ends.
- Counting queries in a test against the in-memory store of
designing repositories: it
checks the rules but runs no query, so the count test runs against the
mapping tool and a real store.
Related skills
Further reading
- Identity and units of work
- Loading and query counts
1---2name: oo-taming-persistence3description: Use when choosing active record or a data mapper, when a list fires one query per row, or when lazily loaded data fails outside its session.4license: MIT5metadata:6 source: https://skillmd.com/skills/yutna/oo-taming-persistence7 version: 0.21.08 pack: object-oriented-design-skills9---1011# Taming Persistence1213**In this pack:**14[sizing](../oo-design/SKILL.md#how-much-design-a-task-warrants),15[notation](../oo-design/references/notation.md),16[rule strictness](../oo-design/SKILL.md#how-strictly-a-rule-is-meant).1718## Overview1920A domain model and a store drift apart unless one object owns the21translation between them. This skill chooses an active record while a22class still mirrors one table row, moves to a data mapper once the23class's fields or rules part from that row, and keeps every mapping24decision at the edge. It also keeps one object per identity within a25transaction, scopes the store's session to one use case, holds lazy26loads inside their aggregate and their transaction, and fills a list27with one read query whose count a test checks.2829## When to use3031- A module is choosing between an active record and a data mapper.32- A domain class extends the mapping tool's base class, carries its33 markers, or has a setter that only the mapping tool uses.34- A list screen or a report runs one query for each row it shows.35- Lazily loaded data is touched after the request's session has closed,36 or once for each item of a list.37- Two copies of one appointment are loaded in one use case.38- A store session is opened once and kept across requests.3940## When not to use4142- The question is what a repository offers, such as its query methods,43 specifications or query objects: that is44 [designing repositories](../oo-designing-repositories/SKILL.md).45- The question is which objects must change and be stored together in46 one transaction: that is47 [designing aggregates](../oo-designing-aggregates/SKILL.md).48- The store holds nothing the domain model rebuilds, such as an49 append-only log or a cache of computed figures.50- The question is giving reads a separate model of their own, kept51 current from the changes: that is52 [separating reads from writes](../oo-separating-reads-from-writes/SKILL.md),53 which builds it as a projection of the changes.5455## Core rules56571. Judgement. **Choose an active record, an object that is one table58 row and saves itself, while a module's classes mirror its tables and59 hold few rules, and a data mapper, a separate object that moves data60 between domain objects and the store, once a class's fields or rules61 part from its table.** [Placing domain62 logic](../oo-placing-domain-logic/SKILL.md) rule 1 decides how a63 module organises its logic, and this choice follows it: transaction64 scripts sit well on active records, while a domain model needs a65 mapper. What tips the balance is whether each class still matches one66 table row and holds no rule that spans rows.67682. Rule. **With a data mapper, keep every mapping decision in the69 adapter: table and column names, the stored row's shape, and how an70 aggregate is rebuilt.** Give the mapper nothing the domain would not71 give any caller: no public setter and no public constructor added for72 it. Where the mapper cannot rebuild through the class's own factory,73 as [designing repositories](../oo-designing-repositories/SKILL.md)74 rule 2 asks, map into a separate stored record and convert it in the75 adapter, and keep the mapping tool's markers off domain classes, the76 way the exception to77 [inverting dependencies](../oo-inverting-dependencies/SKILL.md) rule78 4 keeps a framework's markers off them.79803. Rule. **Within one transaction, answer one object for one identity:81 the identity map of the store's session, or the repository itself,82 returns the object it already loaded rather than a second copy.** An83 identity map is the session's record of the object it loaded for each84 identity. Two copies of one appointment in one use case each take a85 change, and whichever is saved last silently drops the other's.86874. Rule. **Begin and end a unit of work, the session that tracks the88 objects it loaded and writes their changes at commit, exactly where89 the application service opens and ends the transaction90 ([placing domain logic](../oo-placing-domain-logic/SKILL.md) rule 2):91 one unit of work per use case.** A session kept across requests92 answers objects other users have since changed, and writes changes93 nobody meant to save. Whether changes reach the store by tracking or94 by an explicit save stays95 [designing repositories](../oo-designing-repositories/SKILL.md) rule96 5.97985. Rule. **Let no lazy load cross an aggregate's boundary or outlive99 its transaction: load each aggregate whole ([designing100 repositories](../oo-designing-repositories/SKILL.md) rule 6) and101 reach another aggregate by its identity through its own repository102 ([designing aggregates](../oo-designing-aggregates/SKILL.md) rule 3).**103 Lazy loading loads an association when it is first touched, not with104 its aggregate, so a lazy reference runs a query at that moment, which105 may be in a screen after the session has closed, where it fails, or106 once for each item of a list.1071086. Default. **Fill a list with one read query that returns the rows it109 shows, rather than loading aggregates and touching their110 associations one by one, and assert in a test how many queries the111 use case runs.** A query per row is one read for each item, so the112 count grows with the list, and a test that counts queries finds it113 before a busy clinic day does. The read query is the one114 [layering the system](../oo-layering-the-system/SKILL.md) rule 6115 lets a decision-free read use.116117 The exception is a list whose length cannot grow, such as one118 clinician's breaks in a day: a query per item costs a fixed few.119120## Pattern121122Before, the active record `Appointment` is one table row that saves123itself, and `CompleteAppointment` asks it for a status change that124writes the row at once. After, `Appointment` is a domain object with no125knowledge of its row, `Appointments` is the port that finds and saves126it, and `MappedAppointments` keeps the store's session behind that port.127128Before:129130```text131class Appointment extends StoredRecord132 - status: AppointmentStatus133 + static findById(id: AppointmentId): Appointment134 + changeStatus(next: AppointmentStatus): void135 status := next136 save()137138class CompleteAppointment139 + run(id: AppointmentId): void140 appointment := Appointment.findById(id)141 appointment.changeStatus(Completed)142 return143```144145`findById` is taken to read the row stored under an `AppointmentId`146and build the appointment, and `save()` is the message `StoredRecord`147answers, so `changeStatus` writes that appointment's row, in the148clinic's database, at once, outside any transaction a use case opened.149`AppointmentStatus` is the150[modeling lifecycles](../oo-modeling-lifecycles/SKILL.md) skill's151four-member enumeration, and `Completed` is one of its members. The152fence shows only the status field, because the row's other columns play153no part here. Any caller can send `changeStatus` any status, so the154appointment never refuses a move its lifecycle forbids.155156After:157158```text159class Appointment160 - id: AppointmentId161 - slot: Slot162 - patient: PatientId163 - status: AppointmentStatus164 - new(id: AppointmentId, slot: Slot, patient: PatientId,165 status: AppointmentStatus)166 + static book(id: AppointmentId, slot: Slot,167 patient: PatientId): Appointment168 slot.reserve(patient)169 return new Appointment(id, slot, patient, Scheduled)170 + static restore(id: AppointmentId, slot: Slot, patient: PatientId,171 status: AppointmentStatus): Appointment172 return new Appointment(id, slot, patient, status)173 + id(): AppointmentId174 return id175 + complete(): void176 raises AppointmentNotCompletable177 if status = InProgress then178 status := Completed179 else180 raise AppointmentNotCompletable181 return182183interface Appointments184 + find(id: AppointmentId): Appointment185 raises AppointmentNotFound186 + save(appointment: Appointment): void187188class MappedAppointments implements Appointments189 - session: StoreSession190 + new(session: StoreSession)191 + find(id: AppointmentId): Appointment192 raises AppointmentNotFound193 return session.load(id)194 + save(appointment: Appointment): void195 session.store(appointment)196 return197198class CompleteAppointment199 - appointments: Appointments200 + new(appointments: Appointments)201 + run(id: AppointmentId): void202 appointment := appointments.find(id)203 appointment.complete()204 appointments.save(appointment)205 return206```207208`Appointment` keeps the209[designing repositories](../oo-designing-repositories/SKILL.md) skill's210shape, which adds `- id: AppointmentId` first, a private constructor211that takes it, `book`, `restore` and `id()`; `notation.md`'s sketch212leaves that field out. `complete()` is the213[modeling lifecycles](../oo-modeling-lifecycles/SKILL.md) skill's214transition: it raises `AppointmentNotCompletable` unless the status is215`InProgress`, and otherwise sets it to `Completed`. The appointment216extends nothing.217218`interface Appointments` offers `find`, which raises219`AppointmentNotFound`, and `save`; it leaves out the port's `add` and220`forClinicianOn`, which this use case never sends. `MappedAppointments`221holds a `StoreSession` set by its constructor: `find` returns222`session.load(id)` and `save` sends `session.store(appointment)`.223`CompleteAppointment` holds the port set by its constructor and sends224`find`, `complete()` and `save`, once each.225226`StoredRecord` and `StoreSession` stand for any mapping tool's own227types, and this skill names no mapping tool. `session.load(id)` is taken228to rebuild the appointment from its row through `Appointment.restore`,229to answer the same object again for the same identity within the230session, and to raise `AppointmentNotFound` when no row has that231identity. `session.store` is taken to write the whole appointment at232commit. What is stored is the completed appointment, under its233`AppointmentId`, in the clinic's database, in the transaction `run`234opens, with the session opened and closed with it; the fence leaves235both boundaries out.236237Each version changes the status once and stores it once: the Before238version through `changeStatus` and `save()`, the After version through239`complete()` and `appointments.save`.240241## Red flags242243Places to look, not verdicts. A red flag becomes a finding only with244evidence: a measurement, a reproducible bug, or a failing test.245246- A domain class that extends the mapping tool's base class, or carries247 its markers.248- A public setter or a public no-argument constructor that exists only249 for the mapping tool.250- A list screen or a report whose query count grows with its rows.251- An association loaded on first touch that crosses to another252 aggregate.253- A store session kept open across requests or screens.254- Two objects for one identity in one use case.255256## Common mistakes257258- Adopting a data mapper for a module of a few independent rules that259 mirror their tables.260- Turning on eager loading everywhere to cure a query per row.261- Letting a template or a view touch an association the use case did262 not load.263- Saving an object in the middle of a use case, before its transaction264 ends.265- Counting queries in a test against the in-memory store of266 [designing repositories](../oo-designing-repositories/SKILL.md): it267 checks the rules but runs no query, so the count test runs against the268 mapping tool and a real store.269270## Related skills271272- [oo-design](../oo-design/SKILL.md) sizes a task and defines the rule273 labels.274- [oo-designing-repositories](../oo-designing-repositories/SKILL.md)275 gives each aggregate a port that speaks in domain types and keeps the276 store behind it.277- [oo-designing-aggregates](../oo-designing-aggregates/SKILL.md) draws278 the boundary a lazy load must not cross.279- [oo-placing-domain-logic](../oo-placing-domain-logic/SKILL.md) gives280 the use case its transaction and keeps each rule in the domain.281- [oo-layering-the-system](../oo-layering-the-system/SKILL.md) lets a282 decision-free read take a read query at the edge.283284## Further reading285286- [Identity and units of work](references/identity-and-units-of-work.md)287- [Loading and query counts](references/loading-and-query-counts.md)