Designing Repositories
In this pack:
sizing,
notation,
rule strictness.
Overview
A repository is where the domain finds and stores its aggregates. It
should read like a collection of whole aggregates, speak in the domain's
types, and keep every storage detail on the outside. When it grows a
method per screen, answers with rows, or writes one field by identity,
it has stopped being a collection and become a window onto a table. This
skill gives each aggregate root one repository, names its queries for
the questions the clinic asks, and chooses how a change reaches the
store. The aim is domain code that can be read, tested and changed
without knowing where its objects live.
When to use
- A repository has grown a method per screen or report.
- A repository answers with rows, maps or partial records instead of
whole aggregates.
- A caller changes one field by identity, such as a status.
- You are deciding where a new aggregate is loaded from and saved to.
- A search's criteria combine freely, and each caller builds its own
query.
- A domain class holds a connection, query text or a storage marking.
When not to use
- The object is not an aggregate root: an inner entity, a value, or a
plain record a report reads.
- The code is a report or an export that reads rows and changes
nothing. A plain query that returns data serves it, and no aggregate
is loaded.
- The question is how domain code reaches any outside service through a
port and an adapter wired at the composition root, not how aggregates
are stored and found. That is
inverting dependencies.
Core rules
Rule. Give each aggregate root one repository that reads like a
collection of whole aggregates: add a new one, find one by its
identity, remove one, and nothing that hands out an inner part.
Name it for what it holds, such as Appointments; a name with
Repository in it is fine where callers need to know they are asking a
store, as
naming classes and methods
allows. An inner entity has no repository of its own.
Rule. Declare the repository's interface in the domain, in the
domain's types only, and implement it at the edge: no connection,
row, query text or storage session crosses the interface, and no
domain class knows how it is stored. The interface and its
implementation are the port and the adapter of
inverting dependencies, and
the implementation rebuilds each aggregate through a factory of its
class, such as the notation's Appointment.restore, so no field is
set from outside the class.
Default. Name each query for the question the domain asks, such as
forClinicianOn(clinician, date), and return whole aggregates, not a
general findBy(field, value) or a query builder handed to
callers. A name says which clinic question it answers, so a reader
knows what comes back without opening the implementation.
The exception is a search whose criteria combine freely, such as a
reception search by any mix of clinician, date range and kind of
appointment. Rule 4 gives that search a shape.
Judgement. Give a query a specification or a query object when the
named methods multiply. A specification is a domain object that
answers whether one aggregate meets a rule, so the same rule checks
one aggregate and, translated by the implementation, selects many. A
query object carries a search's criteria to the repository, which
turns them into the store's query. What tips the balance is how many
query methods the repository has grown, and whether one rule is
needed both to check one object and to select many.
Judgement. Choose how changes reach the store: a repository that
keeps track of the aggregates it handed out and stores their changes
when the transaction ends, or one with an explicit save(aggregate)
that the caller sends after each change. What tips the balance is
whether the storage code beneath the repository tracks changes for
you; without that, an explicit save is plain and easy to test.
Either way, the application service that opens the transaction
decides when it ends, not the repository.
Rule. Change an aggregate only by loading it whole, sending its
root the change and storing it whole: no updateStatus(id, status)
or other method that writes one field behind the root. That is rule
2 of designing aggregates. A
screen that needs a few fields of many aggregates reads them through
a separate read query that returns plain data, not through the
repository.
Pattern
Before, FinishConsultation asks a data-access object to overwrite a
status. The appointment's own rule never runs, so an appointment that
never started can be marked completed. After, the use case asks the
store for the appointment, sends it complete() and saves it.
Before:
class AppointmentDao
- connection: DatabaseConnection
+ new(connection: DatabaseConnection)
+ findByClinicianIdAndDate(clinicianId: String,
date: String): List<AppointmentRow>
return connection.query(
"appointments of one clinician on one day",
clinicianId, date)
+ updateStatus(id: String, status: String): void
connection.execute(
"the status of one appointment by its id", status, id)
return
class FinishConsultation
- dao: AppointmentDao
+ new(dao: AppointmentDao)
+ run(id: String): void
dao.updateStatus(id, "completed")
return
connection.query(text, ...) is taken to run one read query and answer
its rows, connection.execute(text, ...) to run one write statement
once, and the text is a string literal that says what the call asks,
with the values sent beside it as arguments; the store's own query
language stays outside this skill. AppointmentRow is taken to be the
store's row, not an appointment. findByClinicianIdAndDate answers rows
for one clinician and one day, and updateStatus writes one status by
id, so a caller decides the appointment's next state.
FinishConsultation.run sends "completed" for any id, so an
appointment that never started is marked completed and the appointment's
own rule never runs. "completed" is the status text the table stores.
What updateStatus stores is one status column, in the store the
connection reaches, in the transaction FinishConsultation.run opens
and ends; the fence leaves those boundaries out.
After:
interface Appointments
+ add(appointment: Appointment): void
+ find(id: AppointmentId): Appointment
raises AppointmentNotFound
+ forClinicianOn(clinician: ClinicianId, date: Date): List<Appointment>
+ save(appointment: Appointment): void
class FinishConsultation
- appointments: Appointments
+ new(appointments: Appointments)
+ run(id: AppointmentId): void
appointment := appointments.find(id)
appointment.complete()
appointments.save(appointment)
return
The port is
inverting dependencies's
Appointments, which declares add, and
modeling lifecycles adds due to
it; this fence shows the add it keeps and the three methods this skill
adds, find, forClinicianOn and save, and leaves due as that
skill writes it. A store named AppointmentRepository plays the same
role, and find keeps the name
deciding object or data sends
to its AppointmentRepository. The store finds and saves an appointment
by the AppointmentId it carries, which notation.md's sketch of
Appointment leaves out. The example takes the explicit save of
rule 5, so FinishConsultation.run opens the transaction and ends it
once save has written the appointment; the fence leaves those
boundaries out. What is stored is the whole appointment, in the
Appointments store, in that transaction. complete() is the
lifecycles skill's transition, and it refuses an appointment that is
not in progress, so the appointment's own rule runs. The change touches
the appointment alone: no other aggregate is read or saved.
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 repository method per screen or report, each named for a list of
fields.
- A repository that returns rows, maps or partial records instead of
aggregates.
- A method that writes one field by identity, such as
updateStatus(id, status).
- A repository for an inner entity of an aggregate.
- Query text, a connection or a storage session in a domain class.
- A repository that commits its own transaction inside each call.
Common mistakes
- Copying a table's columns into the repository's method names.
- Handing callers a general query builder in the name of flexibility.
- Saving part of an aggregate to make one screen faster.
- Giving a domain class storage markings or a base class from the
storage library.
- Testing the domain only against the real database, because the
repository has no in-memory implementation.
Related skills
Further reading
- Specifications and query objects
- Persistence ignorance
1---2name: oo-designing-repositories3description: Use when designing a repository, when it grows a find method per screen, returns rows instead of objects, or updates single fields.4license: MIT5metadata:6 source: https://skillmd.com/skills/yutna/oo-designing-repositories7 version: 0.21.08 pack: object-oriented-design-skills9---1011# Designing Repositories1213**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 repository is where the domain finds and stores its aggregates. It21should read like a collection of whole aggregates, speak in the domain's22types, and keep every storage detail on the outside. When it grows a23method per screen, answers with rows, or writes one field by identity,24it has stopped being a collection and become a window onto a table. This25skill gives each aggregate root one repository, names its queries for26the questions the clinic asks, and chooses how a change reaches the27store. The aim is domain code that can be read, tested and changed28without knowing where its objects live.2930## When to use3132- A repository has grown a method per screen or report.33- A repository answers with rows, maps or partial records instead of34 whole aggregates.35- A caller changes one field by identity, such as a status.36- You are deciding where a new aggregate is loaded from and saved to.37- A search's criteria combine freely, and each caller builds its own38 query.39- A domain class holds a connection, query text or a storage marking.4041## When not to use4243- The object is not an aggregate root: an inner entity, a value, or a44 plain record a report reads.45- The code is a report or an export that reads rows and changes46 nothing. A plain query that returns data serves it, and no aggregate47 is loaded.48- The question is how domain code reaches any outside service through a49 port and an adapter wired at the composition root, not how aggregates50 are stored and found. That is51 [inverting dependencies](../oo-inverting-dependencies/SKILL.md).5253## Core rules54551. Rule. **Give each aggregate root one repository that reads like a56 collection of whole aggregates: `add` a new one, `find` one by its57 identity, `remove` one, and nothing that hands out an inner part.**58 Name it for what it holds, such as `Appointments`; a name with59 Repository in it is fine where callers need to know they are asking a60 store, as61 [naming classes and methods](../oo-naming-classes-and-methods/SKILL.md)62 allows. An inner entity has no repository of its own.63642. Rule. **Declare the repository's interface in the domain, in the65 domain's types only, and implement it at the edge: no connection,66 row, query text or storage session crosses the interface, and no67 domain class knows how it is stored.** The interface and its68 implementation are the port and the adapter of69 [inverting dependencies](../oo-inverting-dependencies/SKILL.md), and70 the implementation rebuilds each aggregate through a factory of its71 class, such as the notation's `Appointment.restore`, so no field is72 set from outside the class.73743. Default. **Name each query for the question the domain asks, such as75 `forClinicianOn(clinician, date)`, and return whole aggregates, not a76 general `findBy(field, value)` or a query builder handed to77 callers.** A name says which clinic question it answers, so a reader78 knows what comes back without opening the implementation.7980 The exception is a search whose criteria combine freely, such as a81 reception search by any mix of clinician, date range and kind of82 appointment. Rule 4 gives that search a shape.83844. Judgement. **Give a query a specification or a query object when the85 named methods multiply.** A specification is a domain object that86 answers whether one aggregate meets a rule, so the same rule checks87 one aggregate and, translated by the implementation, selects many. A88 query object carries a search's criteria to the repository, which89 turns them into the store's query. What tips the balance is how many90 query methods the repository has grown, and whether one rule is91 needed both to check one object and to select many.92935. Judgement. **Choose how changes reach the store: a repository that94 keeps track of the aggregates it handed out and stores their changes95 when the transaction ends, or one with an explicit `save(aggregate)`96 that the caller sends after each change.** What tips the balance is97 whether the storage code beneath the repository tracks changes for98 you; without that, an explicit `save` is plain and easy to test.99 Either way, the application service that opens the transaction100 decides when it ends, not the repository.1011026. Rule. **Change an aggregate only by loading it whole, sending its103 root the change and storing it whole: no `updateStatus(id, status)`104 or other method that writes one field behind the root.** That is rule105 2 of [designing aggregates](../oo-designing-aggregates/SKILL.md). A106 screen that needs a few fields of many aggregates reads them through107 a separate read query that returns plain data, not through the108 repository.109110## Pattern111112Before, `FinishConsultation` asks a data-access object to overwrite a113status. The appointment's own rule never runs, so an appointment that114never started can be marked completed. After, the use case asks the115store for the appointment, sends it `complete()` and saves it.116117Before:118119```text120class AppointmentDao121 - connection: DatabaseConnection122 + new(connection: DatabaseConnection)123 + findByClinicianIdAndDate(clinicianId: String,124 date: String): List<AppointmentRow>125 return connection.query(126 "appointments of one clinician on one day",127 clinicianId, date)128 + updateStatus(id: String, status: String): void129 connection.execute(130 "the status of one appointment by its id", status, id)131 return132133class FinishConsultation134 - dao: AppointmentDao135 + new(dao: AppointmentDao)136 + run(id: String): void137 dao.updateStatus(id, "completed")138 return139```140141`connection.query(text, ...)` is taken to run one read query and answer142its rows, `connection.execute(text, ...)` to run one write statement143once, and the text is a string literal that says what the call asks,144with the values sent beside it as arguments; the store's own query145language stays outside this skill. `AppointmentRow` is taken to be the146store's row, not an appointment. `findByClinicianIdAndDate` answers rows147for one clinician and one day, and `updateStatus` writes one status by148id, so a caller decides the appointment's next state.149`FinishConsultation.run` sends `"completed"` for any id, so an150appointment that never started is marked completed and the appointment's151own rule never runs. `"completed"` is the status text the table stores.152What `updateStatus` stores is one status column, in the store the153connection reaches, in the transaction `FinishConsultation.run` opens154and ends; the fence leaves those boundaries out.155156After:157158```text159interface Appointments160 + add(appointment: Appointment): void161 + find(id: AppointmentId): Appointment162 raises AppointmentNotFound163 + forClinicianOn(clinician: ClinicianId, date: Date): List<Appointment>164 + save(appointment: Appointment): void165166class FinishConsultation167 - appointments: Appointments168 + new(appointments: Appointments)169 + run(id: AppointmentId): void170 appointment := appointments.find(id)171 appointment.complete()172 appointments.save(appointment)173 return174```175176The port is177[inverting dependencies](../oo-inverting-dependencies/SKILL.md)'s178`Appointments`, which declares `add`, and179[modeling lifecycles](../oo-modeling-lifecycles/SKILL.md) adds `due` to180it; this fence shows the `add` it keeps and the three methods this skill181adds, `find`, `forClinicianOn` and `save`, and leaves `due` as that182skill writes it. A store named `AppointmentRepository` plays the same183role, and `find` keeps the name184[deciding object or data](../oo-deciding-object-or-data/SKILL.md) sends185to its `AppointmentRepository`. The store finds and saves an appointment186by the `AppointmentId` it carries, which `notation.md`'s sketch of187`Appointment` leaves out. The example takes the explicit `save` of188rule 5, so `FinishConsultation.run` opens the transaction and ends it189once `save` has written the appointment; the fence leaves those190boundaries out. What is stored is the whole appointment, in the191`Appointments` store, in that transaction. `complete()` is the192lifecycles skill's transition, and it refuses an appointment that is193not in progress, so the appointment's own rule runs. The change touches194the appointment alone: no other aggregate is read or saved.195196## Red flags197198Places to look, not verdicts. A red flag becomes a finding only with199evidence: a measurement, a reproducible bug, or a failing test.200201- A repository method per screen or report, each named for a list of202 fields.203- A repository that returns rows, maps or partial records instead of204 aggregates.205- A method that writes one field by identity, such as206 `updateStatus(id, status)`.207- A repository for an inner entity of an aggregate.208- Query text, a connection or a storage session in a domain class.209- A repository that commits its own transaction inside each call.210211## Common mistakes212213- Copying a table's columns into the repository's method names.214- Handing callers a general query builder in the name of flexibility.215- Saving part of an aggregate to make one screen faster.216- Giving a domain class storage markings or a base class from the217 storage library.218- Testing the domain only against the real database, because the219 repository has no in-memory implementation.220221## Related skills222223- [oo-design](../oo-design/SKILL.md) sizes a task and defines the rule224 labels.225- [oo-inverting-dependencies](../oo-inverting-dependencies/SKILL.md)226 gives the domain a port and puts its adapter at the edge.227- [oo-designing-aggregates](../oo-designing-aggregates/SKILL.md) draws228 the boundary a repository keeps whole.229- [oo-hiding-implementation](../oo-hiding-implementation/SKILL.md)230 keeps the store's own types and errors from reaching a caller.231- [oo-taming-persistence](../oo-taming-persistence/SKILL.md) keeps the232 mapping tool's sessions, identity map and loading in check behind the233 repository.234235## Further reading236237- [Specifications and query objects](references/specifications-and-query-objects.md)238- [Persistence ignorance](references/persistence-ignorance.md)