Repository and Unit of Work
What you will learn on this page
Section titled “What you will learn on this page”- What a repository is: an interface that looks like a collection of one kind of aggregate and hides how it is stored.
- What a unit of work is: one business transaction that tracks the changes made through its repositories and keeps all of them or none.
- How to give both an in-memory and a file-backed implementation, and test them with one contract test.
- How to write a file so a reader never sees half of it, and how to rebuild aggregates so a bad file is refused.
- What the pattern costs, and what it does not solve: two transactions that overwrite each other.
The problem: the maps must become storage
Section titled “The problem: the maps must become storage”On the DDD page, the Registry kept every course and student load in
two std::maps, and committed a command by moving two copies into
them. That has three limits:
- Nothing survives a restart. The registrar wants the term’s enrollments kept in a file, and later perhaps a database.
- The application code names the maps. Changing to a file means editing every use case.
- “Both or neither” is done by hand in each command, with two moves that only work for memory. A file or a database needs a different way to keep two changes together.
Two patterns split the work. A repository answers “where are the courses?” with an interface that looks like a collection. A unit of work answers “which changes belong together?” and keeps them in one step. The names are commonly associated with Martin Fowler’s Patterns of Enterprise Application Architecture (2002), and Repository also with Eric Evans’s Domain-Driven Design (2003).
Step 1: classify the classes
Section titled “Step 1: classify the classes”| Class | Kind | Owns | Knows about |
|---|---|---|---|
CourseRepository |
interface (port) | nothing | the domain |
LoadRepository |
interface (port) | nothing | the domain |
UnitOfWork |
interface (port) | nothing | the two repositories |
Storage |
interface (port), a factory | nothing | units of work |
StagedUnitOfWork |
adapter, shared | the pending changes, its two repositories | the storage’s tables |
MemoryStorage |
adapter | the tables | nothing else |
FileStorage |
adapter | a copy of the file’s tables, the path | the file format |
Registry |
application | nothing; refers to a Storage |
the ports, the domain |
The data members follow from the “owns” column. The application has no data members that hold aggregates at all, only non-owning pointers to the storage and the notification stream it was given. The adapters hold the aggregates, and only the adapters know whether they are in memory or in a file.
Text description of the diagram
Three groups. The application group holds the Registry. The ports group holds three interfaces: Storage with begin, UnitOfWork with courses, loads, and commit, and the two repositories with find and add. The adapters group holds StagedUnitOfWork, MemoryStorage, FileStorage, and the file format. The Registry uses Storage, UnitOfWork, the two repositories, and the domain. StagedUnitOfWork implements UnitOfWork and the two repositories. MemoryStorage and FileStorage implement Storage and both create StagedUnitOfWork objects. FileStorage uses the file format, which reads and writes the file enrollment_store.txt. The ports refer to the domain types. No arrow goes from the application to an adapter.
Diagram source (Mermaid)
flowchart LR
subgraph App["application"]
Registry["Registry"]
end
subgraph Ports["store, the ports"]
Storage["Storage<br/>begin"]
Work["UnitOfWork<br/>courses, loads, commit"]
Repos["CourseRepository and<br/>LoadRepository, find and add"]
end
subgraph Adapters["adapters"]
Staged["StagedUnitOfWork"]
Memory["MemoryStorage"]
File["FileStorage"]
Format["file format<br/>write and read"]
end
Disk[("enrollment_store.txt")]
Domain["domain<br/>Course, StudentLoad, enroll"]
Registry --> Storage
Registry --> Work
Registry --> Repos
Registry --> Domain
Staged -.->|implements| Work
Staged -.->|implements| Repos
Memory -.->|implements| Storage
File -.->|implements| Storage
Memory --> Staged
File --> Staged
File --> Format
Format --> Disk
Ports --> DomainThe repositories
Section titled “The repositories”A repository is written in the domain’s terms: find a course by its code, add a course. It does not say “row”, “file”, or “query”.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A repository looks like a collection of one aggregate type, in the// domain's terms, and hides how the aggregates are stored. It hands out// copies: change the copy, then add it back. Nothing reaches storage// until the unit of work that owns the repository commits.// These are interfaces (abstract classes): every function is `virtual ...// = 0`, so the class only lists what a repository can do, and each// storage adapter writes a class that derives from it and fills them in.// The application calls them through a reference and never learns which// adapter is behind it.class CourseRepository {public: // A virtual destructor, so that destroying an adapter through a // CourseRepository pointer or reference runs the adapter's destructor. virtual ~CourseRepository() = default;
// A copy of the course as this unit of work sees it, or nothing. // Returning by value (inside std::optional) means the caller owns the // copy: no pointer into the storage can dangle, and changing the copy // changes nothing stored until it is given back with add. An empty // optional means "no such course"; it is not an error. virtual std::optional<domain::Course> find(const domain::CourseCode& code) const = 0; // Records a new or changed course, replacing any with the same code. // The repository keeps its own copy; the caller's object is not kept. virtual void add(const domain::Course& course) = 0;
// Protected special members: only derived classes can construct or // copy the base part. Outside code cannot copy "a CourseRepository" // and slice an adapter down to its interface by accident.protected: CourseRepository() = default; CourseRepository(const CourseRepository&) = default; CourseRepository& operator=(const CourseRepository&) = default;};
// The same contract for the other aggregate root, StudentLoad, found by// its StudentId.class LoadRepository {public: virtual ~LoadRepository() = default;
virtual std::optional<domain::StudentLoad> find(const domain::StudentId& student) const = 0; virtual void add(const domain::StudentLoad& load) = 0;
protected: LoadRepository() = default; LoadRepository(const LoadRepository&) = default; LoadRepository& operator=(const LoadRepository&) = default;};Two decisions shape this interface:
findreturns a copy, in astd::optional. A file or a database has no object to point into, so a copy is the simplest answer every storage can give. The caller changes the copy and gives it back withadd. The hexagonal page’sCourseStoreport made the same choice, for the same reason; it was already a small repository.- There is one repository per aggregate root, not per class.
There is no
SeatRepository, because seats are inside a course and are reached only through it. Saving a course saves its seats and waitlist.
The unit of work
Section titled “The unit of work”The repositories belong to a unit of work, and changes reach storage only when it commits:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// One business transaction. It tracks what was added through its two// repositories, and commit keeps all of it or none of it. A unit of work// destroyed without commit keeps nothing.// That last rule is what makes early returns and exceptions safe: the// caller does not have to remember to "roll back"; leaving the scope that// owns the unit of work is the rollback.class UnitOfWork {public: virtual ~UnitOfWork() = default;
// The unit's repositories. They are returned by reference: the unit of // work owns them, and a reference is valid only while it lives. virtual CourseRepository& courses() = 0; virtual LoadRepository& loads() = 0; // Keeps every change added since the start or the last commit. Throws // if the changes could not be kept; then none of them are. virtual void commit() = 0;
protected: UnitOfWork() = default; UnitOfWork(const UnitOfWork&) = default; UnitOfWork& operator=(const UnitOfWork&) = default;};
// Where units of work come from. The application begins one per command.class Storage {public: virtual ~Storage() = default;
// The unit of work refers to this storage and must not outlive it. // std::unique_ptr: the caller becomes the only owner of the new unit // of work, and it is destroyed (keeping nothing, unless committed) // when that pointer goes out of scope. It is returned as a pointer to // the interface because each storage makes its own derived class. virtual std::unique_ptr<UnitOfWork> begin() = 0;
protected: Storage() = default; Storage(const Storage&) = default; Storage& operator=(const Storage&) = default;};Storage::begin returns the unit of work by std::unique_ptr, so the
caller owns it and it ends when the command ends. The rule “destroyed
without commit keeps nothing” makes the common path safe: a command
that returns early, or throws before committing, keeps nothing. This is the same idea as
the copies on the DDD page, but behind an interface that a file or a
database can implement.
Storage is a factory interface, as on the composition root
page: the Registry is given one
long-lived storage, and asks it for a short-lived unit of work per
command.
One unit of work for both stores
Section titled “One unit of work for both stores”Both adapters keep their data in the same shape, a map per aggregate type, so they can share one unit-of-work class:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Every stored aggregate, keyed by its root's id. Both storage adapters// keep their data in this shape, and a unit of work keeps its pending// changes in it too.// A plain struct of two maps, copied and moved by value. std::map keeps// its keys sorted, which is why the file lists courses and students in// order of their ids.struct Tables { std::map<domain::CourseCode, domain::Course> courses; std::map<domain::StudentId, domain::StudentLoad> loads;};
// Returns `base` with every entry of `changes` added or replaced.// `base` is taken by value, so the function works on its own copy: the// caller's tables are not changed, and if copying or inserting throws,// they are still exactly as they were.Tables merged(Tables base, const Tables& changes);VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The unit of work both storage adapters share. Reads see the committed// tables with this unit's own changes on top. Commit hands the changes// to the storage's keep function, which must keep all of them or throw.// `final` means no class may derive from this one.class StagedUnitOfWork final : public store::UnitOfWork {public: // The type of the storage's keep function: anything that can be called // with the pending changes and returns nothing. std::function can hold // a lambda, so each storage passes a short lambda instead of a class. using Keep = std::function<void(const Tables& changes)>;
// `committed` is the storage's data and must outlive this object. // Stores the address of the storage's tables (no copy is made) and // takes over the keep function with std::move. StagedUnitOfWork(const Tables& committed, Keep keep) : committed_{&committed}, keep_{std::move(keep)} {} // The repositories point back at this object, so it stays where it is. StagedUnitOfWork(const StagedUnitOfWork&) = delete; StagedUnitOfWork& operator=(const StagedUnitOfWork&) = delete; // (Declaring the copy operations deleted also means the compiler makes // no move operations, so the object cannot be moved either.)
// `override` asks the compiler to check that these really replace the // interface's virtual functions. Each returns one of the members below. store::CourseRepository& courses() override { return courses_; } store::LoadRepository& loads() override { return loads_; } void commit() override;
private: // The two repositories are nested classes, so they may use the unit of // work's private members (changes_ and committed_) through owner_. // They hold no data of their own. class Courses final : public store::CourseRepository { public: explicit Courses(StagedUnitOfWork& owner) : owner_{&owner} {} std::optional<domain::Course> find(const domain::CourseCode& code) const override; void add(const domain::Course& course) override;
private: StagedUnitOfWork* owner_; // the unit of work that contains this object };
class Loads final : public store::LoadRepository { public: explicit Loads(StagedUnitOfWork& owner) : owner_{&owner} {} std::optional<domain::StudentLoad> find(const domain::StudentId& student) const override; void add(const domain::StudentLoad& load) override;
private: StagedUnitOfWork* owner_; };
// Members are built top to bottom, so courses_ and loads_ come last. // While being built they only store `this` (the address of the object // being built); they use it later, in a find or add, when all exist. const Tables* committed_; // non-owning, never null Tables changes_; // added since the start or the last commit Keep keep_; Courses courses_{*this}; Loads loads_{*this};};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Each repository function is one line that forwards to its owner's data.// look_up (defined above this region) checks this unit's changes first and// the committed tables second, and returns a copy of what it finds, or// std::nullopt. So a command sees its own uncommitted changes, and nobody// else does. owner_->committed_->courses reads "the courses in the// storage's tables that this unit of work points at".std::optional<domain::Course> StagedUnitOfWork::Courses::find(const domain::CourseCode& code) const { return look_up(owner_->changes_.courses, owner_->committed_->courses, code);}
// Stages the course: only changes_ is touched, never the storage.// insert_or_assign adds a new entry, or overwrites the entry with the same// key, so adding the same course twice keeps the later version. It stores// a copy of `course`.void StagedUnitOfWork::Courses::add(const domain::Course& course) { owner_->changes_.courses.insert_or_assign(course.code(), course);}
std::optional<domain::StudentLoad> StagedUnitOfWork::Loads::find( const domain::StudentId& student) const { return look_up(owner_->changes_.loads, owner_->committed_->loads, student);}
void StagedUnitOfWork::Loads::add(const domain::StudentLoad& load) { owner_->changes_.loads.insert_or_assign(load.student(), load);}
// Hands every staged change to the storage in one call. The order of the// two lines is the whole rule:// - keep_ throws: the storage promised to keep nothing, the exception// leaves commit before the second line, so changes_ still holds every// staged change (and destroying the unit of work discards them).// - keep_ returns: the storage has kept everything, so the staged// changes are cleared, and a later commit sends only newer changes.void StagedUnitOfWork::commit() { keep_(changes_); // if this throws, the changes stay pending here changes_ = Tables{}; // kept: start the next batch empty}How this code works: What a StagedUnitOfWork sees, keeps, and drops
Who owns what. The storage owns tables_, the committed data. The
caller of begin owns the unit of work through a std::unique_ptr.
The unit of work owns changes_ and its two repository objects, and
only points at the storage’s tables through committed_. The
repositories own nothing; each points back at the unit of work that
contains it.
A worked example. The storage holds CS101, which has 2 seats, with S1 and S2 seated. One command begins a unit of work and enrolls S3:
courses().find(CS101)callslook_up.changes_has no CS101, so it returns a copy of the committed CS101: S1 and S2 seated.- The command waitlists S3 on its copy and calls
courses().add(copy).insert_or_assignputs a copy intochanges_. The storage still holds the old CS101. - A second
find(CS101)in the same unit of work now finds the entry inchanges_first and returns S1 and S2 seated, S3 waiting. Any other unit of work still sees only the committed version. commit()callskeep_(changes_). Then one of two things happens:keep_returns: the storage now holds the new CS101, andchanges_is cleared;keep_throws: the storage holds the old CS101, the exception leavescommitbeforechanges_is cleared, and the staged CS101 is still inchanges_.
- When the unit of work is destroyed,
changes_is destroyed with it. After a successful commit it is empty, so nothing is lost; after a failed commit or no commit at all, the staged changes are discarded. Nothing is ever written back on destruction: the destructor does no work of its own, which is what “destroyed without commit keeps nothing” means in code.
How the members are chosen:
changes_is the unit of work’s own data: what was added and not yet kept. Reads look there first, so a command sees its own changes.committed_is a pointer to the storage’s tables, not a copy. Starting a unit of work copies nothing; the storage must outlive it, which the interface states.keep_is how the storage keeps the changes. Astd::functionlets each storage pass a lambda instead of writing another class.- The two repositories are member objects that point back at the unit of work. Because of those pointers the class deletes its copy operations, which also prevents moving it: a copied repository would still point at the original.
class adapters::StagedUnitOfWork
implements store::UnitOfWork
Data members
const Tables* committed_;non-owning, the storage's dataTables changes_;added since the start or the last commitstd::function<void(const Tables&)> keep_;all or nothing, or throwsCourses courses_;a CourseRepository that points back hereLoads loads_;a LoadRepository that points back here
Member functions
StagedUnitOfWork(const Tables& committed, Keep keep);committed must outlive thisStagedUnitOfWork(const StagedUnitOfWork&) = delete;and copy assignment; no move eitherstore::CourseRepository& courses() override;store::LoadRepository& loads() override;void commit() override;
class adapters::MemoryStorage
implements store::Storage
Data members
Tables tables_;
Member functions
std::unique_ptr<store::UnitOfWork> begin() override;
class adapters::FileStorage
implements store::Storage
Data members
std::filesystem::path path_;Tables tables_;the file's content, as last read or writtenvoid keep(const Tables& changes);
Member functions
explicit FileStorage(std::filesystem::path path);std::unique_ptr<store::UnitOfWork> begin() override;
The in-memory storage
Section titled “The in-memory storage”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Keeps everything in memory: for tests, and for programs that need no// persistence. Commit builds the merged tables first and then moves them// into place, a move that cannot throw, so a failed commit changes nothing.// Each begin() makes a new StagedUnitOfWork that reads tables_ and whose// keep function replaces tables_ with the merged result. The units of work// point at this object, so it must outlive every one of them.class MemoryStorage final : public store::Storage {public: std::unique_ptr<store::UnitOfWork> begin() override;
private: Tables tables_; // everything committed so far; starts empty};Its begin passes a lambda that does tables_ = merged(tables_, changes). merged takes its first argument by value, so it builds
the new tables in a copy; if that throws, tables_ is untouched. The
move assignment into tables_ cannot throw, which a static_assert
in memory_storage.cpp checks. The cost is a copy of every stored
aggregate per commit: fine for tests and small programs, and the first
thing to change if the in-memory store held many thousands of
courses.
The file storage
Section titled “The file storage”A text file cannot have one line replaced in place, so every commit writes the whole content again:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Keeps everything in one text file. A text file cannot be changed in// place, so commit writes the whole new content to a temporary file next// to it and renames that over the old one. The rename replaces the file// in one step, so a reader sees the old content or the new, never half// of each.class FileStorage final : public store::Storage {public: // Reads `path` if it exists. Throws std::runtime_error if it cannot be // read or a line breaks the format or a rule. If it throws, no // FileStorage exists, so nothing can use half-read data. explicit FileStorage(std::filesystem::path path);
// Like MemoryStorage: a new unit of work over tables_, whose commit // calls keep. The storage must outlive the unit of work. std::unique_ptr<store::UnitOfWork> begin() override;
private: // Writes the merged content to the file and only then updates tables_. // Throws if the file could not be written or renamed; then neither the // file nor tables_ has changed (a .tmp file may be left behind). void keep(const Tables& changes);
std::filesystem::path path_; Tables tables_; // the file's content, as last read or written};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The keep function a FileStorage unit of work calls from commit. Each step// either finishes or throws, and nothing visible changes until the rename.void FileStorage::keep(const Tables& changes) { // Step 1: the new content, built in memory. tables_ is copied into // merged's parameter, so tables_ itself is not changed. Tables next = merged(tables_, changes); // Step 2: a temporary file next to the real one, such as // "enrollment_store.txt.tmp". += on a path appends text to the name. std::filesystem::path temporary = path_; temporary += ".tmp"; // The braces make a scope just for the stream (an RAII object): at the // closing brace `out` is destroyed, even if an exception is thrown. { // std::ios::trunc empties the file first if it already exists, so // a .tmp left by an earlier failed commit is overwritten. std::ofstream out{temporary, std::ios::trunc}; write_tables(out, next); // Close first, then check: close flushes the last buffered text, // and a failure while flushing is only seen afterwards. If the // file never opened (such as a missing directory), the stream has // already failed and this check catches that too. out.close(); if (!out) throw std::runtime_error{"cannot write " + temporary.string()}; } // Step 3: replace the real file with the temporary one in one step. // If it throws, the old file is still in place and tables_ unchanged. std::filesystem::rename(temporary, path_); // throws std::filesystem::filesystem_error // Step 4: only now does memory follow the file. Moving `next` hands its // maps over instead of copying them. tables_ = std::move(next); // the file changed, so the copy in memory follows}How this code works: What is left after each failure in FileStorage::keep
A commit reaches keep through the lambda that begin gave the unit of
work: Registry::enroll calls work->commit(), commit calls keep_,
and keep_ calls FileStorage::keep. If any step in keep throws, the
exception travels back up the same path: commit skips clearing
changes_, Registry::enroll skips publish, and the unit of work is
destroyed as the exception leaves enroll, discarding its changes.
| Step that fails | enrollment_store.txt |
.tmp file |
tables_ in memory |
|---|---|---|---|
1. merged runs out of memory |
old content | not touched | old content |
| 2. opening, writing, or closing the temporary file | old content | missing or incomplete | old content |
3. rename |
old content | complete, left behind | old content |
none: keep returns |
new content | gone (it became the real file) | new content |
In every failure row the real file and the copy in memory agree with each other, so the next unit of work reads the same data that is on disk. Only the last row changes anything a reader can see, and the rename is the single moment where that happens.
The order of steps is what makes it all or nothing:
- Build the merged tables in memory. Nothing has changed yet.
- Write them to
enrollment_store.txt.tmp, and check the stream after closing it. A full disk or a missing directory throws here, and the real file is untouched. - Rename the temporary file over the real one. POSIX guarantees that
renameon one file system replaces the target in one step, so another reader sees the old file or the new one. - Only then update the copy in memory.
The format, and reading through the roots
Section titled “The format, and reading through the roots”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The text format of the file store, one record per line:// course CS101 2 Software Design// seated S1 S2// waiting S3// load S3 CS101 MA101// A course's seated and waiting lines follow its course line, in order.// The words are separated by single spaces; the title is everything after// the capacity. An empty list is written as the label alone ("waiting").// write_tables writes every course (with its two lines), then every load.// It does not report errors itself: the caller checks the stream.void write_tables(std::ostream& out, const Tables& tables);
// Rebuilds the aggregates through their roots, so a file that breaks a// rule is refused. Throws std::runtime_error naming the bad line, such as// "line 2: breaks the course's rules"; on a throw, nothing read so far is// returned. Blank lines are skipped.Tables read_tables(std::istream& in);VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Reads one line at a time and decides what it is from its first word.// Helpers defined above this region: split cuts a line into words (views// into `line`, not copies); parse_or_refuse<Id> parses an id or throws// naming the line; refuse(number, why) always throws std::runtime_error// with "line N: why". The function builds a local Tables and returns it// only when every line was accepted.Tables read_tables(std::istream& in) { Tables tables; // A pointer to the course most recently read, so that the seated and // waiting lines below it know where to go. nullptr until the first // course line: a seated line before any course is "not understood". // Pointing into a std::map is safe here: adding more entries to a map // never moves the existing ones. domain::Course* current = nullptr; // the course the seated and waiting lines belong to std::string line; // getline reads the next line into `line` and is false at the end of // the input; `number` counts lines from 1 for the error messages. for (std::size_t number = 1; std::getline(in, line); ++number) { // `words` views the text in `line`, so it is used only in this pass, // before the next getline overwrites `line`. const std::vector<std::string_view> words = split(line); if (words.empty()) continue; if (words[0] == "course" && words.size() >= 3) { const auto code = parse_or_refuse<domain::CourseCode>(words[1], number); // std::from_chars reads an int from the characters of words[2]. // It returns where it stopped (`end`) and an error code; the // capacity is accepted only if there was no error, every // character was used (so "2x" is refused), and it is at least 1. int capacity = 0; const auto [end, error] = std::from_chars(words[2].data(), words[2].data() + words[2].size(), capacity); if (error != std::errc{} || end != words[2].data() + words[2].size() || capacity < 1) { refuse(number, "bad capacity"); } // The title is the rest of the line; the words are views into it. // Subtracting two pointers into the same text gives the offset // of the capacity word in `line`; adding its length and 1 (the // space after it) gives where the title starts. For // "course CS101 2 Software Design" that is 13 + 1 + 1 = 15. // No title after the capacity gives an empty title. const auto title_at = static_cast<std::size_t>(words[2].data() - line.data()) + words[2].size() + 1; std::string title = title_at < line.size() ? line.substr(title_at) : std::string{}; // emplace adds the entry only if the code is new. It returns a // pair, unpacked here: `where` points at the entry with that // code, and `added` says whether this call made it. const auto [where, added] = tables.courses.emplace(code, domain::Course{code, std::move(title), capacity}); if (!added) refuse(number, "course " + code.text() + " appears twice"); current = &where->second; // later seated/waiting lines fill this course } else if ((words[0] == "seated" || words[0] == "waiting") && current != nullptr) { // Replay the enrollments in order: seats fill first, then the // waitlist, so the root rebuilds the same state and checks it. // Every id on a "seated" line must be seated by enroll, and every // id on a "waiting" line must be waitlisted. Any other answer is // a broken rule: more seated than the capacity (enroll says // waitlisted), a student waiting while a seat is free (enroll // says seated), or the same student twice (already_in_course). const auto expected = words[0] == "seated" ? domain::JoinResult::seated : domain::JoinResult::waitlisted; // From 1, because words[0] is the label. for (std::size_t i = 1; i < words.size(); ++i) { const auto student = parse_or_refuse<domain::StudentId>(words[i], number); if (current->enroll(student) != expected) refuse(number, "breaks the course's rules"); } // enroll recorded an event per student; take them and drop the // result, so a later take_events does not report them as new. current->take_events(); // rebuilding is not news } else if (words[0] == "load" && words.size() >= 2) { // The same replay for a load: join each listed course through the // root. A fourth course (at_limit) or a repeated one // (already_joined) is refused; both are reported as // "breaks the limit". const auto student = parse_or_refuse<domain::StudentId>(words[1], number); domain::StudentLoad load{student}; for (std::size_t i = 2; i < words.size(); ++i) { const auto code = parse_or_refuse<domain::CourseCode>(words[i], number); if (load.join(code) != domain::LoadResult::joined) refuse(number, "breaks the limit"); } // The load is complete, so it is moved into the map. .second is // the "was it added" flag of the pair emplace returns. if (!tables.loads.emplace(student, std::move(load)).second) { refuse(number, "student " + student.text() + " appears twice"); } } else { // Anything else: an unknown first word, too few words, or a // seated or waiting line before any course line. refuse(number, "not understood"); } } return tables; // every line was accepted}How this code works: read_tables, line by line
read_tables keeps two things between lines: the Tables it is
building, and current, a pointer to the course read most recently.
Each line is split into words, and the first word decides what the
line is. Any problem calls refuse, which throws, so the half-built
Tables is destroyed and never returned.
A worked example. This is the file the program below writes after its first script:
| Line | Text | What happens |
|---|---|---|
| 1 | course CS101 2 Software Design |
CS101 is created with capacity 2 and the title from position 15 on; current points at it |
| 2 | seated S1 S2 |
enroll(S1) and enroll(S2) must both answer seated, and they do; the two events are taken |
| 3 | waiting S3 |
both seats are taken, so enroll(S3) answers waitlisted, as required |
| 4 | course MA101 30 Linear Algebra |
MA101 is created; current now points at MA101 |
| 5 | seated S3 |
S3 is seated in MA101 |
| 6 | waiting |
no ids, so the loop does not run: MA101 has an empty waitlist |
| 7–9 | load S1 CS101 and so on |
each load is rebuilt by join, one course at a time, and stored |
current stays valid while more courses are added, because a
std::map never moves an entry it already holds.
When the file is wrong. With a one-seat CS101 and the line
seated S1 S2, enroll(S2) answers waitlisted, not seated, so
line 2 is refused with line 2: breaks the course's rules. The same
check refuses a waiting line while a seat is free, and a student
listed twice. A seated line before any course line is “not
understood”, because current is still nullptr.
Building an object from stored data is often called rehydration.
The reader does not set seated_ and waitlist_ directly; it cannot,
because they are private. It replays the enrollments through
Course::enroll, in the stored order. Seats fill first and the
waitlist after, so the root rebuilds the same state, and it checks
every rule while doing so: a file with two students in a one-seat
course is refused, with the line number. The replay records events,
which the reader takes and throws away, because rebuilding a course is
not news.
Replaying is cheap here and needs no new code in the domain. If replay were slow or the domain’s functions had side effects, the usual alternative is a constructor or factory function that takes the whole state and checks the invariants once, written for this purpose.
The reader checks each aggregate on its own. It does not check that the courses and the loads agree with each other, for example that S3’s load lists CS101 exactly when CS101 holds S3. The program keeps them in step by committing both together; a hand-edited file could break that and would not be refused.
The application, now with storage
Section titled “The application, now with storage”The Registry has no maps any more, only the storage it was given:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The application layer of the aggregate page, now with storage behind// the repository interfaces. Each command begins one unit of work, finds// the aggregates it needs, lets the domain decide, adds the changed// aggregates back, and commits. It never names a file or a map.class Registry {public: // Both must outlive this object. // The registry stores only their addresses. It is given a Storage // interface, so main can hand it a FileStorage and a test a // MemoryStorage, with no change to this class. Registry(store::Storage& storage, std::ostream& notifications) : storage_{&storage}, out_{¬ifications} {}
std::string add_course(std::string_view code, int capacity, const std::string& title); std::string add_student(std::string_view id); std::string enroll(std::string_view student, std::string_view course); std::string drop(std::string_view student, std::string_view course); // Queries: `const`, and they never commit. std::string load(std::string_view student) const; std::string report(std::string_view course) const;
private: void publish(const std::vector<domain::CourseEvent>& events);
store::Storage* storage_; // non-owning, never null std::ostream* out_; // non-owning, never null};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The enroll use case, with storage behind interfaces: parse, begin a unit// of work, find copies, let the domain decide, add the changes, commit,// publish. Returns the reply line. Throws whatever commit throws (such as// std::runtime_error from a failed file write); then nothing was kept and// nothing was published.std::string Registry::enroll(std::string_view student, std::string_view course) { // Malformed text is refused before any storage work starts. const auto id = domain::StudentId::parse(student); const auto code = domain::CourseCode::parse(course); if (!id) return "refused: no student " + std::string{student}; if (!code) return "refused: no course " + std::string{course};
// One unit of work for the whole command. // `work` is the only owner of the unit of work. Every return below, and // any exception, destroys it at the end of this function, and a unit // of work destroyed without a commit keeps nothing. const std::unique_ptr<store::UnitOfWork> work = storage_->begin(); // find returns a copy inside an optional; empty means not stored. std::optional<domain::StudentLoad> load = work->loads().find(*id); if (!load) return "refused: no student " + id->text(); std::optional<domain::Course> target = work->courses().find(*code); if (!target) return "refused: no course " + code->text();
// The domain changes the two copies (*load and *target are the values // inside the optionals), or refuses and leaves them alone. const domain::EnrollDecision decision = domain::enroll(*load, *target); // Only seated and waitlisted change anything; the other two are refusals. const bool changed = decision.status == domain::EnrollStatus::seated || decision.status == domain::EnrollStatus::waitlisted; if (changed) { // Take the events first, so the stored copy does not carry them. const std::vector<domain::CourseEvent> events = target->take_events(); work->loads().add(*load); work->courses().add(*target); // If commit throws, the exception leaves enroll here: publish is // skipped, and `work` is destroyed with its changes still pending. work->commit(); // both or neither; throws if storage fails publish(events); // only after the change is kept } // a refusal adds nothing, and the unit of work ends without a commit
// Word the reply. Every case returns; the last line is never reached. switch (decision.status) { case domain::EnrollStatus::seated: return "ok: " + id->text() + " enrolled in " + code->text(); case domain::EnrollStatus::waitlisted: return "ok: " + id->text() + " waitlisted for " + code->text() + " (position " + std::to_string(decision.position) + ")"; case domain::EnrollStatus::already_in_course: return "refused: " + id->text() + " is already in " + code->text(); case domain::EnrollStatus::at_course_limit: return "refused: " + id->text() + " already has " + std::to_string(domain::StudentLoad::max_courses) + " courses"; } return "refused: " + id->text() + " is already in " + code->text(); // not reached}How this code works: One enroll command through the layers, with storage
Follow enroll S3 CS101 from the first script.
mainpasses the line torun_command, which callsregistry.enroll("S3", "CS101").Registry::enroll(application) parses both ids. It owns nothing long-lived: it points at the storage and the stream it was given.storage_->begin()returns a newStagedUnitOfWork. The localworkowns it for the rest of the function.findon each repository returns copies of the stored load and course. The local optionalsloadandtargetown those copies.domain::enroll(*load, *target)(domain) changes the copies: S3’s load gains CS101, and S3 joins the CS101 waitlist.- The events are taken from the course copy, both copies are added
to the unit of work (which stores its own copies in
changes_), andcommitasks the storage to keep them, which for a file store rewrites the file. publishprints the notification, the reply is returned, andworkis destroyed at the closing brace ofenroll.
What is left after each kind of ending:
| How the command ends | Storage (file and memory) | Printed |
|---|---|---|
| Malformed id (step 2) | unchanged; no unit of work | only the refused: reply |
| Unknown student or course (step 4) | unchanged; the unit of work is dropped unused | only the refused: reply |
| Domain refusal (step 5) | unchanged; nothing was added or committed | only the refused: reply |
commit throws (step 6) |
unchanged; the staged changes die with work |
nothing; enroll throws |
| Success | both aggregates changed together | the notifications, then the reply |
The exception in the fourth row is not caught by Registry, by
run_command, or by main, so in the example program it would end
the program; the test below catches it with LLD_CHECK_THROWS.
Three details matter:
- The events are taken before the course is added back.
addstores a copy of the course; if that copy still held the events, both stores would keep it in memory (the file store until a restart), and the next command that found the course would publish them again. - A refusal commits nothing. The unit of work is destroyed at the end of the function, and its rule says that keeps nothing. A file store does not rewrite the file for a refused command.
- The events are published after
commitreturns. If the commit throws, nobody is told. If publishing fails after the commit, the change is kept and the notice is lost; the DDD page’s outbox note applies.
Queries use the same interfaces and never commit:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Queries use a unit of work too, and simply never commit.// The unit of work here is a temporary: begin() returns a unique_ptr that// lives only until the end of this statement (the `;`). That is safe// because find returns a copy, so `found` does not refer to the unit of// work after it is gone. A malformed id gives std::nullopt, the same as an// unknown one, so both are refused with the same reply.std::string Registry::load(std::string_view student) const { const auto id = domain::StudentId::parse(student); const std::optional<domain::StudentLoad> found = id ? storage_->begin()->loads().find(*id) : std::nullopt; if (!found) return "refused: no student " + std::string{student}; return "ok: " + id->text() + " has " + std::to_string(found->courses().size()) + " of " + std::to_string(domain::StudentLoad::max_courses) + " courses: " + join_ids(found->courses());}Text description of the diagram
A sequence diagram for one enroll command with a file store. The Registry asks the FileStorage to begin, and gets a new unit of work. It asks the StagedUnitOfWork to find the load and the course, and gets copies, with the unit’s own changes taking priority. It asks the domain service to enroll the load into the course, and the answer is waitlisted. The Registry takes the events from the course copy, then adds the load and the course to the unit of work and commits. The unit of work asks the storage to keep the changes. The storage writes the temporary file, renames it over the store file, and reports that the changes are kept, and the unit of work reports the commit. The Registry publishes the events and words the reply. The unit of work is destroyed when the command ends.
Diagram source (Mermaid)
sequenceDiagram
participant R as Registry
participant S as FileStorage
participant W as StagedUnitOfWork
participant D as domain enroll
participant F as file system
R->>S: begin
S-->>R: a new unit of work
R->>W: find the load and the course
W-->>R: copies, own changes first
R->>D: enroll the load into the course
D-->>R: waitlisted
R->>R: take the events from the course copy
R->>W: add the load and the course
R->>W: commit
W->>S: keep the changes
S->>F: write the temporary file
S->>F: rename it over the store file
S-->>W: kept
W-->>R: committed
R->>R: publish the events, word the reply
R->>W: destroy at the end of the commandRunning it
Section titled “Running it”The program runs a first script against a file store, prints the file, then starts a new storage from the same file and runs a second script, as a restarted program would:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Shows that the data survives a "restart": the first script runs against// a FileStorage, the file is printed, then a brand-new FileStorage reads// the same file and the second script carries on from there. run (defined// above this region) prints each command after "> " and then its reply.int main() { // The store is a file in the current directory. Start without one, so // every run prints the same. const std::filesystem::path path = "enrollment_store.txt"; std::filesystem::remove(path); // removes the file if it exists; no error if not
constexpr std::string_view first_run[] = { "course CS101 2 Software Design", "course MA101 30 Linear Algebra", "student S1", "student S2", "student S3", "enroll S1 CS101", "enroll S2 CS101", "enroll S3 CS101", "enroll S3 MA101", }; constexpr std::string_view second_run[] = { "report CS101", "drop S1 CS101", "enroll S3 CS101", "report CS101", "load S3", };
// A block, so the storage and registry are destroyed at its closing // brace. The registry is declared second, so it is destroyed first, // while the storage it points at still exists. { adapters::FileStorage storage{path}; // no file yet: starts empty app::Registry registry{storage, std::cout}; run(registry, first_run); } // the program "stops": the storage and registry are gone, the file stays
std::cout << "--- " << path.string() << " ---\n"; // Print the whole file: the two istreambuf_iterators mean "from the // first character of the file" and (the `{}`) "to its end", and the // string is built from every character in between. std::ifstream file{path}; std::cout << std::string{std::istreambuf_iterator<char>{file}, {}}; std::cout << "--- restart ---\n";
{ adapters::FileStorage storage{path}; // reads the file again app::Registry registry{storage, std::cout}; run(registry, second_run); } std::filesystem::remove(path); // tidy up, so the next run starts clean too}> course CS101 2 Software Designok: course CS101 added> course MA101 30 Linear Algebraok: course MA101 added> student S1ok: student S1 added> student S2ok: student S2 added> student S3ok: student S3 added> enroll S1 CS101notify S1: you have a seat in CS101ok: S1 enrolled in CS101> enroll S2 CS101notify S2: you have a seat in CS101ok: S2 enrolled in CS101> enroll S3 CS101notify S3: you are number 1 on the waitlist for CS101ok: S3 waitlisted for CS101 (position 1)> enroll S3 MA101notify S3: you have a seat in MA101ok: S3 enrolled in MA101--- enrollment_store.txt ---course CS101 2 Software Designseated S1 S2waiting S3course MA101 30 Linear Algebraseated S3waitingload S1 CS101load S2 CS101load S3 CS101 MA101--- restart ---> report CS101ok: CS101 Software Design, 2/2 seats taken seated: S1, S2 waitlist: S3> drop S1 CS101notify S3: a seat opened; you are enrolled in CS101ok: S1 left CS101> enroll S3 CS101refused: S3 is already in CS101> report CS101ok: CS101 Software Design, 2/2 seats taken seated: S2, S3 waitlist: (none)> load S3ok: S3 has 2 of 3 courses: CS101, MA101The second storage knows nothing the first one did not write to the
file, yet it reports S3 on the waitlist, promotes S3 when S1 drops, and
refuses enroll S3 CS101 because S3 is already in it. The domain code
is the DDD page’s, unchanged: only the storage moved.
Testing
Section titled “Testing”One contract, two storages. The rules of the interfaces are written
once, as a function that takes any Storage, and run against both
adapters:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// What every Storage must do, written once and run against both.// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure// if the condition is false, and LLD_CHECK_EQ(actual, expected) compares// with == and prints both values when they differ. They come from the// site's small test header, lld_test.hpp. code("CS101") and student("S1"),// defined above this region, turn text known to be valid into ids.namespace {
// Takes the storage by reference to the interface, so the same checks run// unchanged on any adapter. Expects an empty storage.void check_storage_contract(store::Storage& storage) { { // a unit of work sees its own changes before it commits const std::unique_ptr<store::UnitOfWork> work = storage.begin(); work->courses().add(domain::Course{code("CS101"), "Software Design", 2}); LLD_CHECK(work->courses().find(code("CS101")).has_value()); } // ended without commit // A fresh unit of work, used for one line and then destroyed. LLD_CHECK(!storage.begin()->courses().find(code("CS101")).has_value()); // nothing kept
{ // commit keeps changes to both repositories const std::unique_ptr<store::UnitOfWork> work = storage.begin(); domain::Course course{code("CS101"), "Software Design", 2}; course.enroll(student("S1")); course.take_events(); // events are not stored; clear them as the registry does domain::StudentLoad load{student("S1")}; load.join(code("CS101")); work->courses().add(course); work->loads().add(load); work->commit(); } // destroyed after the commit: what was kept stays kept // A later unit of work sees both committed aggregates. const std::unique_ptr<store::UnitOfWork> later = storage.begin(); const std::optional<domain::Course> course = later->courses().find(code("CS101")); const std::optional<domain::StudentLoad> load = later->loads().find(student("S1")); LLD_CHECK(course.has_value() && course->contains(student("S1"))); LLD_CHECK(load.has_value() && load->courses().count(code("CS101")) == 1);
// find hands out copies: changing one changes nothing stored std::optional<domain::Course> copy = later->courses().find(code("CS101")); // -> on an optional reaches the course inside it (the test knows it is // there). enroll's result is not needed. copy->enroll(student("S2")); LLD_CHECK_EQ(later->courses().find(code("CS101"))->seated().size(), std::size_t{1});}
} // namespace
// The contract on each adapter. Each test makes its own empty storage.LLD_TEST(memory_storage_keeps_the_contract) { adapters::MemoryStorage storage; check_storage_contract(storage);}
LLD_TEST(file_storage_keeps_the_contract) { const std::filesystem::path path = "contract_store.txt"; std::filesystem::remove(path); // start with no file, so the storage is empty // The block ends the storage before the file is removed below. { adapters::FileStorage storage{path}; check_storage_contract(storage); } std::filesystem::remove(path);}A third storage, for example one for a database, would add a three-line test that calls the same function.
What only the file storage does: read back what another storage object wrote, read a stored file back through the roots, refuse a file that breaks a rule, and keep nothing when a write fails:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// LLD_TEST, LLD_CHECK, LLD_CHECK_EQ and LLD_CHECK_THROWS come from// lld_test.hpp; LLD_CHECK_THROWS(expression, type) fails unless the// expression throws that type. Helpers defined above this region: code and// student make ids from valid text; write_file(path, text) writes a file.// Each test that makes a file uses its own name and removes it at the end.
// Setup: one storage commits CS101 (1 seat) with S1 seated and S2 waiting,// then is destroyed. Proves: a second storage on the same file finds the// course with the same title, capacity, seat, and waitlist.LLD_TEST(what_one_storage_writes_the_next_one_reads) { const std::filesystem::path path = "round_trip_store.txt"; std::filesystem::remove(path); { adapters::FileStorage first{path}; const std::unique_ptr<store::UnitOfWork> work = first.begin(); domain::Course course{code("CS101"), "Software Design", 1}; course.enroll(student("S1")); course.enroll(student("S2")); course.take_events(); work->courses().add(course); work->commit(); } // the first storage is gone; only the file is left adapters::FileStorage second{path}; const std::optional<domain::Course> course = second.begin()->courses().find(code("CS101")); LLD_CHECK(course.has_value()); LLD_CHECK_EQ(course->title(), std::string{"Software Design"}); LLD_CHECK_EQ(course->capacity(), 1); LLD_CHECK(course->seated().size() == 1 && course->seated().front() == student("S1")); LLD_CHECK(course->waitlist().size() == 1 && course->waitlist().front() == student("S2")); std::filesystem::remove(path);}
// Setup: a file written by hand, with S2 and S3 waiting in that order.// Proves: the reader keeps the waitlist order and leaves no events behind.LLD_TEST(a_stored_file_is_read_back_through_the_roots) { const std::filesystem::path path = "restart_store.txt"; write_file(path, "course CS101 1 Software Design\nseated S1\nwaiting S2 S3\nload S2 CS101\n"); adapters::FileStorage storage{path}; const std::unique_ptr<store::UnitOfWork> work = storage.begin(); std::optional<domain::Course> course = work->courses().find(code("CS101")); LLD_CHECK(course.has_value()); LLD_CHECK_EQ(course->title(), std::string{"Software Design"}); LLD_CHECK(course->waitlist().front() == student("S2")); // order kept LLD_CHECK(course->take_events().empty()); // rebuilding is not news std::filesystem::remove(path);}
// Setup: a one-seat course whose file lists two seated students.// Proves: the constructor throws, and the message names line 2. S2 is the// one refused: replaying enroll puts S2 on the waitlist, not in a seat.LLD_TEST(a_file_that_breaks_a_rule_is_refused_with_its_line) { const std::filesystem::path path = "broken_store.txt"; write_file(path, "course CS101 1 Software Design\nseated S1 S2\n"); // two in one seat // try/catch keeps the message so the test can check its exact text. // If nothing were thrown, `message` would stay empty and the check // below would fail. std::string message; try { adapters::FileStorage storage{path}; } catch (const std::runtime_error& error) { message = error.what(); } LLD_CHECK_EQ(message, std::string{"line 2: breaks the course's rules"}); std::filesystem::remove(path);}
// Setup: a store whose directory does not exist. The constructor finds no// file and starts empty, but no file can be written there.// Proves: commit throws std::runtime_error ("cannot write ..."), and a new// unit of work still finds no CS101, so the failed commit kept nothing.LLD_TEST(a_failed_write_keeps_nothing) { adapters::FileStorage storage{"no_such_directory/store.txt"}; const std::unique_ptr<store::UnitOfWork> work = storage.begin(); work->courses().add(domain::Course{code("CS101"), "Software Design", 2}); LLD_CHECK_THROWS(work->commit(), std::runtime_error); LLD_CHECK(!storage.begin()->courses().find(code("CS101")).has_value());}The application with a storage that fails. A small wrapper whose
commit throws shows that the registry publishes nothing for a change
that was not kept, and that a refusal never reaches commit, whether
the command is refused before the domain decides or by the domain:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// LLD_TEST, LLD_CHECK, LLD_CHECK_EQ and LLD_CHECK_THROWS come from// lld_test.hpp; LLD_CHECK_THROWS(expression, type) fails unless the// expression throws that type. std::ostringstream is a stream that writes// into a string, read back with str().namespace {
// A storage whose commits fail, wrapped around a real one. Reads and// adds go to the real storage's unit of work; commit throws instead.class FailingStorage final : public store::Storage {public: explicit FailingStorage(store::Storage& real) : real_{&real} {}
// Wraps the real storage's new unit of work in a FailingWork, which // takes ownership of it. std::unique_ptr<store::UnitOfWork> begin() override { return std::make_unique<FailingWork>(real_->begin()); }
private: class FailingWork final : public store::UnitOfWork { public: explicit FailingWork(std::unique_ptr<store::UnitOfWork> real) : real_{std::move(real)} {} store::CourseRepository& courses() override { return real_->courses(); } store::LoadRepository& loads() override { return real_->loads(); } // Never calls the real commit, so the real unit of work is destroyed // with its changes uncommitted, which keeps nothing. void commit() override { throw std::runtime_error{"disk full"}; }
private: std::unique_ptr<store::UnitOfWork> real_; };
store::Storage* real_; // non-owning, never null};
} // namespace
// Setup: a memory store with CS101 (2 seats), S1, S2, and S2 seated, made// through an ordinary registry. A second registry uses the same data// through FailingStorage.// Proves: when commit fails, enroll throws, prints no notification, and S1// still has no courses; and refusals never reach commit at all.LLD_TEST(a_failed_commit_publishes_nothing_and_keeps_nothing) { adapters::MemoryStorage memory; std::ostringstream ignored; app::Registry setup{memory, ignored}; setup.add_course("CS101", 2, "Software Design"); setup.add_student("S1"); setup.add_student("S2"); setup.enroll("S2", "CS101");
FailingStorage failing{memory}; std::ostringstream out; app::Registry registry{failing, out}; LLD_CHECK_THROWS(registry.enroll("S1", "CS101"), std::runtime_error); LLD_CHECK(out.str().empty()); // nobody was told // Read through the ordinary registry: the stored load is unchanged. LLD_CHECK_EQ(setup.load("S1"), std::string{"ok: S1 has 0 of 3 courses: (none)"});
// A refusal never commits, so even this storage does not fail it: // neither one refused before the domain decides, nor one it refuses. LLD_CHECK_EQ(registry.enroll("S9", "CS101"), std::string{"refused: no student S9"}); LLD_CHECK_EQ(registry.enroll("S2", "CS101"), std::string{"refused: S2 is already in CS101"});}
// Setup: CS101 with one seat, S1 and S2, on a memory store. Proves: the// unchanged registry gives the expected replies and notifications with no// file at all, including S2's promotion when S1 drops.LLD_TEST(the_registry_works_the_same_on_any_storage) { adapters::MemoryStorage memory; std::ostringstream out; app::Registry registry{memory, out}; registry.add_course("CS101", 1, "Software Design"); registry.add_student("S1"); registry.add_student("S2"); LLD_CHECK_EQ(registry.enroll("S1", "CS101"), std::string{"ok: S1 enrolled in CS101"}); LLD_CHECK_EQ(registry.enroll("S2", "CS101"), std::string{"ok: S2 waitlisted for CS101 (position 1)"}); LLD_CHECK_EQ(registry.drop("S1", "CS101"), std::string{"ok: S1 left CS101"}); LLD_CHECK_EQ(out.str(), std::string{"notify S1: you have a seat in CS101\n" "notify S2: you are number 1 on the waitlist for CS101\n" "notify S2: a seat opened; you are enrolled in CS101\n"});}VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
# The ports: repository and unit-of-work interfaces in the domain's terms.# The domain itself is the aggregate page's library, unchanged.add_library(arch_repo_store INTERFACE)target_include_directories(arch_repo_store INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/store)target_link_libraries(arch_repo_store INTERFACE arch_agg_domain)
# Two storage adapters, in memory and in a file, sharing one unit of work.add_library(arch_repo_adapters STATIC adapters/tables.cpp adapters/staged_unit_of_work.cpp adapters/memory_storage.cpp adapters/file_format.cpp adapters/file_storage.cpp)target_include_directories(arch_repo_adapters PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/adapters)target_link_libraries(arch_repo_adapters PUBLIC arch_repo_store)
# The application layer sees only the ports, never an adapter.add_library(arch_repo_app STATIC app/registry.cpp app/commands.cpp)target_include_directories(arch_repo_app PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/app)target_link_libraries(arch_repo_app PUBLIC arch_repo_store)
lld_add_example(arch_enrollment_repository SOURCES main.cpp EXPECTED_OUTPUT expected_output.txt)target_link_libraries(arch_enrollment_repository PRIVATE arch_repo_app arch_repo_adapters)
lld_add_test(arch_repo_contract_tests SOURCES tests/test_storage_contract.cpp)target_link_libraries(arch_repo_contract_tests PRIVATE arch_repo_adapters)
lld_add_test(arch_repo_file_tests SOURCES tests/test_file_storage.cpp)target_link_libraries(arch_repo_file_tests PRIVATE arch_repo_adapters)
lld_add_test(arch_repo_registry_tests SOURCES tests/test_registry.cpp)target_link_libraries(arch_repo_registry_tests PRIVATE arch_repo_app arch_repo_adapters)The CMake libraries set the direction: arch_repo_app links only the
ports, so the adapters’ include directory is not on its include path,
and an application file that included file_storage.hpp would not
build. No test checks that here; the clean architecture
page shows such a check. Only
main and the tests link the adapters.
What it does not solve: the lost update
Section titled “What it does not solve: the lost update”Each unit of work reads, decides, and writes back whole aggregates.
If two units of work are open at the same time, for example in two
threads or two processes sharing the file, both can read the same
course, both can add a student, and the second commit replaces the
first one’s course with its own copy. One enrollment is lost, and no
error is reported. This example’s Registry opens one unit of work at
a time, so it cannot happen here, and its adapters do not detect it.
The adapters are also not safe for other uses. They are not
thread-safe: two threads using one storage would be a data race, which
is undefined behaviour. With two processes, each FileStorage writes
the whole file from the copy it read at start-up, so one process’s
commit discards everything the other committed in the meantime, even
for unrelated courses. Both would also write the same .tmp file, so
the rename would no longer protect readers.
Stores that allow several writers usually prevent it in one of two ways:
- Optimistic concurrency: each aggregate carries a version number. A commit succeeds only if the stored version is still the one that was read, and otherwise fails so the command can be retried.
- Locking: a unit of work locks what it reads until it commits, which is simpler to reason about and makes other writers wait.
Either belongs in the storage adapter and the unit of work, not in the application or the domain.
When the pattern fits
Section titled “When the pattern fits”It pays for itself when:
- the domain has aggregates with rules, and storage is a detail the rules should not see;
- a command changes more than one aggregate, and the changes must be kept together;
- the program needs more than one storage: memory for tests, a file or a database in production.
It costs more than it returns when:
- the program is mostly reading and showing records: a query that returns plain structs straight from storage is shorter, and aggregates are for changes;
- there is one table and simple rules: a single store interface,
like the hexagonal page’s
CourseStore, is enough; - the storage library already gives transactions and change tracking that the team uses well: wrapping it in a second unit of work adds a layer and no protection.
Common mistakes
Section titled “Common mistakes”- A generic
Repository<T>with the same functions for every type. Aggregates need different lookups; a course is found by code, and perhaps listed by department. One interface per root, with the functions the application needs, says more. - Repositories for objects inside an aggregate. A seat repository lets callers change seats without the course, which breaks the course’s rules.
- Committing inside the repository, or in the domain. The application decides what one business transaction is.
- Keeping a unit of work open across commands. It then holds stale copies, and other writers’ changes are hidden from it or overwritten. Begin one per command.
- Forgetting that
findreturns a copy. Changing the copy and not adding it back keeps nothing, without any error. The return type guarantees a copy; the contract test’s last check documents that changing one changes nothing stored. - Taking the events after
add. The stored copy would carry them, and they would be published twice.
When the requirements change
Section titled “When the requirements change”- A database replaces the file. Write
DatabaseStorageand a unit of work over a database transaction:findreads rows into an aggregate,addwrites them inside the transaction, andcommitcommits it. Run the contract test against it. The application, the domain, and the other adapters do not change;mainchooses which storage to build. - Two registrars work at once. Add a version number to each stored
aggregate, and have
commitfail when a version has changed. The application catches that failure and retries the command with a new unit of work. For the file store,commitmust also lock the file, read it again, and compare versions, because its tables are a cached copy. - A new aggregate, such as rooms, gets its own repository, a
rooms()function on the unit of work, and a map inTables. - Billing needs the enrollment history. That is a new read model,
often fed from the events, not a reason to add billing fields to
Course; see the bounded contexts section of the DDD page.
Exercise
Section titled “Exercise”Exercise: Add a query without leaking storage
The registrar wants a new command, waitlists, that lists every
course that has a waitlist, with the number of students waiting, such
as CS101: 3 waiting. Design the change.
- Where does the new function go, and what does it return?
- How does each storage implement it?
- How do you test it?
- What would be wrong with adding
const Tables& all() consttoStorageso the registry can loop over every course itself?
Show the explained answer
One reasonable design:
- A query function on the course repository, in the domain’s
terms:
std::vector<WaitlistSummary> with_waitlists() const, whereWaitlistSummaryis a plain struct holding aCourseCodeand a count. It returns small values, not courses, because the caller only shows them. The registry formats the lines; the repository does not know the text. - Each storage implements it the way it can do best. The shared
StagedUnitOfWorkwalks the stored courses, using its own pending copy of a course in place of the stored one, aslook_updoes, and builds the summaries. Otherwise a course whose waitlist was emptied in this unit would still be listed. A database storage would run one query that counts waitlist rows per course, without rebuilding every course. - Add it to the contract test: store two courses, one with a waitlist, and check that only that one is listed, with its count; and check that a course added but not committed in the same unit of work is included, because the unit sees its own changes, and that a course whose waitlist was emptied in this unit is not listed.
all()leaks the storage: it ties the registry to theTablestype, which a database storage does not have, and it makes every query load every course.Tablesalso lives inadapters, so the ports would depend on an adapter. The contract would no longer be the interface; the data layout would be.
A smaller design that is also defensible: if listing is rare and the
store is small, std::vector<CourseCode> codes() const plus a find
for each one keeps the repository minimal, at the cost of loading every
course. The point is that the query stays in domain terms, behind the
interface.
Summary
Section titled “Summary”- A repository is a collection-like interface for one aggregate root, written in the domain’s terms. Here it hands out copies.
- A unit of work tracks the changes of one business transaction and keeps all of them or none. Begin one per command; commit only when something changed.
- The application uses only the interfaces; adapters decide where the data lives. One unit-of-work class can serve several storages.
- A file store keeps a commit all or nothing by writing a temporary file and renaming it; that is atomic on POSIX, not durable without flushing to disk.
- Rebuild aggregates through their roots, so stored data that breaks a rule is refused.
- One contract test run against every storage keeps them interchangeable.
- The pattern does not prevent lost updates between concurrent units of work; version numbers or locks do.