Skip to content

DTOs, domain objects, and persistence records

Difficulty: Intermediate

Key concepts

  • data transfer object
  • domain object
  • persistence record
  • mapping
  • schema versioning
  • view model
  • boundary
  • Why the data a client sends, the data the domain works with, and the data storage keeps are often three different shapes.
  • How to write each one in C++: plain structs for clients and storage, a class with private data for the domain.
  • How mapping functions turn one shape into another, so that only they, and the code that calls them, know two shapes.
  • How a versioned record lets a new program read rows an old one wrote.
  • What all this costs, and when one type is enough.

The problem: three audiences for one course

Section titled “The problem: three audiences for one course”

The enrollment program gains a web front end. Three parts of the program now deal with a course, and each wants something different:

  • Clients send “enroll S2 in CS101” as text, and ask for a course’s details. They should see how full a course is, but not the ids of the students in it.
  • The domain needs a Course whose seats and waitlist can only change through enroll and drop, so its rules hold.
  • Storage keeps rows. Some rows were written by last year’s program, before waitlists existed, and must still be read.

The tempting answer is one type for all three.

Shape Who uses it C++ form Rules inside? Changes when
Request and reply clients and the API code struct, public members no the API’s contract changes
View clients struct, public members no what clients may see changes
Domain object the domain and use cases class, private members yes, invariants the business rules change
Persistence record storage code struct, flat, with a version no the storage format changes

The “rules inside?” column decides the C++ form. A shape with no rules of its own is a struct with public members: it has no invariant to protect, so code may set its fields freely. Whether the values make sense is checked when they are turned into domain values. A record can still have format limits: this one’s row format cannot hold a | in a title, and write_row does not check that, so a real store would escape separators or refuse such titles. A shape with invariants is a class with private data, changed only through member functions.

The “changes when” column is the reason for separate shapes. Each changes for a different reason, so each can change without the others.

Data flow for one enroll request: text becomes a request DTO, the stored row becomes a record and then a Course, the domain decides, and the changed Course goes back to a record and a row while the result becomes a reply
Text description of the diagram

A data-flow diagram for one enroll request, left to right. The request text “student=S2&course=CS101” is parsed into an EnrollRequest DTO, and its student field is parsed into a StudentId domain value by StudentId::parse. The stored row, in version 1 or 2 of the format, is read into a CourseRecord, and to_domain turns the record into a Course domain object. The student id is passed to Course enroll. The changed Course is turned back into a CourseRecord by to_record, and written as a version 2 row by write_row. The enroll result and the course become an EnrollReply DTO through to_reply, which to_json writes as the JSON reply. Each arrow is one named function.

Diagram source (Mermaid)
flowchart LR
Wire["request text<br/>student=S2&course=CS101"]
Request["EnrollRequest<br/>DTO"]
Id["StudentId<br/>domain value"]
Row["stored row<br/>version 1 or 2"]
Record["CourseRecord<br/>persistence record"]
Course["Course<br/>domain object"]
NewRecord["CourseRecord"]
NewRow["row, version 2"]
Reply["EnrollReply<br/>DTO"]
Json["JSON reply"]
Wire -->|parse_enroll_request| Request
Request -->|StudentId::parse| Id
Row -->|read_row| Record
Record -->|to_domain| Course
Id -->|enroll| Course
Course -->|to_record| NewRecord
NewRecord -->|write_row| NewRow
Course -->|to_reply| Reply
Reply -->|to_json| Json

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

dto.hpp
// Shapes for the outside world: plain structs with no rules and no
// behaviour, only the fields a client sends or receives. Text stays text
// here; the application turns it into domain values.
// These are data transfer objects (DTOs). Every member is public and any
// value is allowed, because a DTO only carries data across a boundary;
// it promises nothing about whether that data makes sense. This header
// includes no domain header, so the API library builds without the domain.
// What the client sent in "POST /enroll student=S1&course=CS101". Both
// fields are the raw text, which may be wrong ("s1", "", "PH999"): the
// application parses student into a domain::StudentId later, and that
// step can refuse it. Keeping it as text here means the request can be
// read before anyone decides whether it is valid.
struct EnrollRequest {
std::string student;
std::string course;
};
// What the client is told after an enrollment request. status is a word
// the client can test for; position is only meaningful for "waitlisted".
// The `= 0` gives the member a default, so EnrollReply{"seated"} sets
// status and leaves position at 0, and to_json then leaves position out.
struct EnrollReply {
std::string status; // "seated", "waitlisted", "already_in_course", ...
std::size_t position = 0; // place on the waitlist, from 1, when waitlisted
};
// What a client may see of a course: counts, not the students' ids.
// The domain Course holds the lists of ids; mapping::to_view copies only
// their sizes into seats_taken and waiting. Leaving the ids out is an API
// decision made once, here, in the type: no JSON writer can leak a field
// that the view does not have.
struct CourseView {
std::string code;
std::string title;
int capacity = 0;
std::size_t seats_taken = 0;
std::size_t waiting = 0;
};

These are data transfer objects (DTOs): plain structs that carry data across a boundary. The term is commonly associated with Martin Fowler’s Patterns of Enterprise Application Architecture; it is used here in its common, wider sense.

Three choices are deliberate:

  • EnrollRequest holds text, not a StudentId. A request is what the client sent, which may be wrong; turning it into domain values is a separate step that can refuse it.
  • CourseView holds counts, not the students. What a client may see is a decision about the API, made here once, not a side effect of what Course happens to store.
  • None of them includes a domain header. The API library compiles without the domain, as the CMake section shows.

Reading and writing the wire format belongs with the client shapes:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

dto.hpp
// Reads "student=S1&course=CS101". A missing field gives std::nullopt;
// the values themselves are not checked here.
// The query is split at each '&' into key=value pairs. Pairs without an
// '=' and keys other than student and course are skipped; if a key comes
// twice, the last value wins. Only "is each field there?" is answered:
// "student=s4&course=CS101" parses fine, and the application refuses the
// "s4" afterwards. The result is std::optional<EnrollRequest>: a box that
// holds a request, or is empty when a field is missing. std::string_view
// is a read-only window onto text owned by the caller, so the query is
// not copied; the request that comes back owns copies of the two values.
std::optional<EnrollRequest> parse_enroll_request(std::string_view query);
// Write a DTO as one line of JSON. They never fail and never throw for
// bad data (only if memory runs out). The reply writes "position" only
// when it is not 0, so a seated reply is just {"status":"seated"}. Text
// fields are put in double quotes, and a quote mark or backslash inside
// the text gets a backslash in front of it.
// Two functions share one name (overloading): the compiler picks the one
// whose parameter type matches the argument.
std::string to_json(const EnrollReply& reply);
std::string to_json(const CourseView& view);

The JSON is written by hand for these few fields, which is enough for the example; a real service would use a JSON library.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

record.hpp
// The shape stored in the table: flat, text and numbers only, and
// versioned, so rows written by an older program can still be read.
// version 2: "2|CS101|Software Design|2|S1,S2|S3"
// version 1: "1|CS101|Software Design|2|S1,S2" (before waitlists)
// A title may not contain '|'.
// Fields, in order: version | code | title | capacity | seated | waiting.
// The two lists are ids joined by ','; an empty list is an empty field,
// so a course with nobody waiting ends in '|' ("...|S1,S2|").
// Like the DTOs, this is a plain struct with no rules: it can hold a
// capacity of 0 or two copies of one id. It mirrors the table, not the
// domain, and includes no domain header.
struct CourseRecord {
// One number shared by all records (static), fixed at compile time
// (constexpr). The version is not a member: a record in memory is
// always "current"; the version only exists in the row text.
static constexpr int current_version = 2;
std::string code;
std::string title;
int capacity = 0;
std::vector<std::string> seated; // ids as text, in enrollment order
std::vector<std::string> waiting; // ids as text, first in line first
};
// Turns a record into a row. A version 1 record does not exist in memory,
// so writing a row that was read as version 1 upgrades it to version 2.
std::string write_row(const CourseRecord& record); // always the current version
// Reads either version. Gives std::nullopt if the row is not in the format;
// the values themselves are not checked here.
// "In the format" means: 5 fields starting with "1", or 6 fields starting
// with "2", and a capacity that is a whole number. Whether "S1" is a real
// student id, or whether the seats fit the capacity, is for the domain.
std::optional<CourseRecord> read_row(std::string_view row);

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

record.cpp
// Turns one stored row into a CourseRecord, or gives std::nullopt when
// the row is in neither known format. It checks shape only: how many
// fields, which version, and that the capacity is a number. It never
// throws for a bad row.
std::optional<CourseRecord> read_row(std::string_view row) {
// split (a helper above) cuts the row at every '|'. The pieces are
// string_views: windows onto the caller's row text, not copies, so
// they are only used inside this function, while the row still exists.
// "1|CS101|Software Design|2|S1" gives five pieces, and a trailing '|'
// gives an empty last piece, so "...|S1|" has one more field.
const std::vector<std::string_view> fields = split(row, '|');
// The version is the first field, and the field count must match it.
// Version 1 rows were written before waitlists, so they have 5 fields.
const bool version_1 = fields.size() == 5 && fields[0] == "1";
const bool version_2 = fields.size() == 6 && fields[0] == "2";
if (!version_1 && !version_2) return std::nullopt; // such as "3|..." or a missing field
CourseRecord record;
// std::string{view} copies the text out of the row, so the record owns
// its own strings and stays valid after the row is gone.
record.code = std::string{fields[1]};
record.title = std::string{fields[2]};
const std::string_view capacity = fields[3];
// std::from_chars reads a number from the characters [first, last) into
// record.capacity. It does not throw: it returns a pointer to the first
// character it did not use, and an error code. `const auto [end, error]`
// unpacks those two results into two names (a structured binding).
const auto [end, error] =
std::from_chars(capacity.data(), capacity.data() + capacity.size(), record.capacity);
// Refuse "two" (no number at all: error is set) and "2x" (a number with
// something left over: end stops at the 'x', short of the end). The
// default std::errc{} means "no error". A negative number such as "-1"
// is a number, so it passes here; to_domain refuses it later.
if (error != std::errc{} || end != capacity.data() + capacity.size()) return std::nullopt;
// list (a helper above) splits a field at ',' into owned strings; an
// empty field gives an empty list rather than one empty id.
record.seated = list(fields[4]);
if (version_2) record.waiting = list(fields[5]); // version 1 had no waitlist
// For version 1, record.waiting is left as it was made: empty. So the
// rest of the program never needs to know that version 1 existed.
return record;
}

The record is flat, uses only text and numbers, and carries a version. Version 1 rows, written before waitlists, have one field fewer; read_row reads both and fills an empty waitlist for version

  1. write_row always writes the current version, so old rows are upgraded the next time they are saved. Neither the domain nor the clients know that version 1 ever existed.

read_row checks the format only: the right number of fields, a number where a number belongs. It does not check that "S1" is a valid student id or that the seats fit the capacity. Those are domain questions, answered in the next step.

The domain shape is the DDD page’s Course, unchanged: private seats, a private waitlist, and enroll and drop as the only ways to change them. The mapping functions sit between it and the other shapes:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

mapping.hpp
// Each function turns one shape into another; none of them decides
// anything about enrollment. The application calls them in order.
// This is the only header that includes all three shapes: the domain's
// course.hpp, the API's dto.hpp, and storage's record.hpp. Each function
// takes its input by const reference (it only reads it) and returns a new
// value of the other shape, so the two never share memory.
// Domain -> stored shape: copies every field, turning ids into text.
// Never fails: a Course always obeys its rules, so any Course can be stored.
persistence::CourseRecord to_record(const domain::Course& course);
// Rebuilds the course through its root, so a record that breaks a rule
// or holds a bad id is refused. Throws std::runtime_error.
// It throws for: a code that is not a valid CourseCode, a capacity below
// 1, an id that is not a valid StudentId, and lists the rules could not
// have produced (too many seated, a duplicate id, someone waiting while a
// seat is free). The events the replay records are thrown away.
domain::Course to_domain(const persistence::CourseRecord& record);
// Domain -> what a client may see: counts only, never the ids.
api::CourseView to_view(const domain::Course& course);
// The domain's answer to enroll -> what the client is told. Needs the
// course too, to read the new waitlist length for a "waitlisted" reply.
api::EnrollReply to_reply(domain::JoinResult result, const domain::Course& course);

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

mapping.cpp
// Domain -> record. The course is only read, through its const getters.
// The braces fill the record's fields in the order they are declared:
// code, title, capacity, seated, waiting. texts (a helper above) copies
// each id's text into a std::vector<std::string>, so the record owns
// plain strings and no longer depends on the Course.
persistence::CourseRecord to_record(const domain::Course& course) {
return persistence::CourseRecord{course.code().text(), course.title(), course.capacity(),
texts(course.seated()), texts(course.waitlist())};
}
// Record -> domain. Course's members are private, so this cannot copy the
// lists in. It builds the course the way any other code must: with the
// constructor, then one enroll call per stored student. If the rules give
// a different answer from what the record says, the record is refused.
domain::Course to_domain(const persistence::CourseRecord& record) {
// parse gives an empty optional for text that is not a course code.
const std::optional<domain::CourseCode> code = domain::CourseCode::parse(record.code);
if (!code) throw std::runtime_error{"stored course has a bad code: " + record.code};
// The constructor throws std::invalid_argument here, which means a
// caller's bug; a stored course with no seats is bad data instead.
// So the same check is made first, with std::runtime_error, which is
// the type EnrollmentApi::handle catches. std::invalid_argument would
// not be caught there and would end the program.
if (record.capacity < 1) throw std::runtime_error{"stored course has no seats: " + record.code};
// *code takes the CourseCode out of the optional; it is known to hold
// one because of the check above. The constructor gets copies.
domain::Course course{*code, record.title, record.capacity};
// Seated students first, in their stored order. While seats are free,
// each enroll answers seated. One id more than the capacity would be
// waitlisted instead, and a repeated id already_in_course; either
// answer makes replay throw.
replay(course, record.seated, domain::JoinResult::seated);
// Then the waitlist, in line order. Each must answer waitlisted, which
// happens only when every seat is taken: someone stored as waiting
// while a seat was free would be seated instead, and is refused.
replay(course, record.waiting, domain::JoinResult::waitlisted);
// Each enroll above also recorded an event (StudentSeated or
// StudentWaitlisted). take_events hands them over and empties the
// course's list; the returned list is not kept, so they are dropped.
course.take_events(); // rebuilding is not news
return course; // by value: the local course is moved out (or built in place), not copied
}
// Domain -> view. The two lists become their sizes, so no id can reach a
// client. course.seated().size() is a std::size_t, the view's type for counts.
api::CourseView to_view(const domain::Course& course) {
return api::CourseView{course.code().text(), course.title(), course.capacity(),
course.seated().size(), course.waitlist().size()};
}
// Domain result -> reply. The switch picks the status word for each
// JoinResult. For waitlisted it also reads the waitlist length: enroll has
// just put the student at the back, so the length is their position,
// counting from 1. The other replies leave position at 0, which to_json
// leaves out.
api::EnrollReply to_reply(domain::JoinResult result, const domain::Course& course) {
switch (result) {
case domain::JoinResult::seated: return api::EnrollReply{"seated"};
case domain::JoinResult::waitlisted:
return api::EnrollReply{"waitlisted", course.waitlist().size()};
case domain::JoinResult::already_in_course: break; // goes on to the return below
}
// Reached for already_in_course. Returning after the switch, not inside
// it, also gives the function a return on every path, which keeps the
// compiler from warning that control could reach the end.
return api::EnrollReply{"already_in_course"};
}
How this code works: mapping::to_domain, replaying a stored course

to_domain has three stages: check what the constructor would refuse, build an empty course, then replay the stored students through enroll. The helper replay (outside the snippet) loops over one list, parses each id with StudentId::parse, calls course.enroll, and throws std::runtime_error if the answer is not the one it expects.

  1. The code. CourseCode::parse(record.code) gives an empty optional for text such as cs101; that throws.
  2. The capacity. A capacity below 1 throws std::runtime_error here, before the Course constructor could throw std::invalid_argument. Only std::runtime_error is caught by EnrollmentApi::handle.
  3. An empty course. The constructor builds a course with the code, title, and capacity, and no students yet.
  4. The seated list, each expected to answer seated.
  5. The waiting list, each expected to answer waitlisted.
  6. The events recorded by every enroll are taken and dropped.
  7. The course is returned by value to the caller, who now owns it.

A record that passes. The row 2|CS101|Software Design|2|S1,S2|S3, which the example’s table ends with:

Step enroll answers Expected Seated, waiting
replay seated, S1 seated seated S1; none
replay seated, S2 seated seated S1, S2; none
replay waiting, S3 waitlisted waitlisted S1, S2; S3

A record that is refused. The row 2|CS101|Software Design|1|S1,S2| from the application test: one seat, two seated students. S1 is seated; S2 finds no free seat, so enroll answers waitlisted, which is not the seated the record claims, and replay throws. The same check catches a student stored as waiting while a seat was free (the answer is seated, not waitlisted) and an id listed twice (the answer is already_in_course).

Each enroll searches both lists for the student first, so replaying 100 students costs thousands of comparisons, growing with the square of the number of students: the quadratic cost the text below mentions.

to_record and to_view read the course through its const functions. to_domain cannot set private members, so it builds the course the way any other code must: through the constructor and enroll, replaying the seated students and then the waiting ones. The root applies its rules as it goes, and to_domain refuses the record with an exception when the result differs from what the record claims, or when an id does not parse. A record with two students in a one-seat course is refused because the root waitlists the second one, although the record says seated; an id like student1 is refused by StudentId::parse. The replay records events, which to_domain discards, because loading a course is not news.

One check is in to_domain itself: a capacity below 1. The Course constructor already refuses that, but with std::invalid_argument, which signals a caller’s bug. A stored course with no seats is bad data, not a bug, so to_domain checks first and throws std::runtime_error, the type handle catches. That is a duplicated precondition, translated into another error type, not a new rule.

Replay has limits. It applies today’s rules to yesterday’s data: if the capacity of a course is lowered, or a new rule is added, old rows that were valid when written may now be refused. It only works when the public functions can reach every state worth storing. And it is slower than copying, here quadratic in the number of students, because each enroll searches the lists. When those limits matter, a common alternative is a restricted factory such as Course::restore(...) that takes the stored state and checks the invariants directly, without replaying the history.

These functions only convert. None of them decides who may enroll. If a mapping function starts to contain an if about business rules, the rule has leaked out of the domain.

struct api::EnrollRequest

DTO, what the client sent

Member functions

  • std::string student;
  • std::string course;

struct api::CourseView

DTO, what a client may see

Member functions

  • std::string code;
  • std::string title;
  • int capacity;
  • std::size_t seats_taken;
  • std::size_t waiting;

struct api::EnrollReply

DTO, what the client is told

Member functions

  • std::string status;
  • std::size_t position;

struct persistence::CourseRecord

stored shape, versioned

Member functions

  • static constexpr int current_version = 2;
  • std::string code;
  • std::string title;
  • int capacity;
  • std::vector<std::string> seated;
  • std::vector<std::string> waiting;

class domain::Course

domain object, from the DDD page

Data members

  • std::vector<StudentId> seated_; size() <= capacity_
  • std::deque<StudentId> waitlist_; empty while a seat is free

Member functions

  • JoinResult enroll(const StudentId& student);

namespace mapping

turns one shape into another

Functions

  • persistence::CourseRecord to_record(const domain::Course& course);
  • domain::Course to_domain(const persistence::CourseRecord& record);
  • api::CourseView to_view(const domain::Course& course);
  • api::EnrollReply to_reply(domain::JoinResult result, const domain::Course& course);
The shapes of the mapping example: plain structs at the boundaries, the domain class between them, and the mapping functions; members are summarized

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

enrollment_api.hpp
// The application, with one shape at each boundary: requests and views
// for clients, rows for the table, and domain objects in between. Its
// table is a map from course code to stored row, so every request reads
// and writes real rows. To keep the mapping in view, this page leaves
// out the student's course limit from the DDD page.
// It owns the table (rows_) by value. No Course lives here between
// requests: each request reads a row, builds a fresh domain::Course from
// it, uses it, and lets it go when the function returns.
class EnrollmentApi {
public:
// The starting table, taken by value and moved into rows_, so the
// caller's map is not copied a second time. `explicit` stops a plain
// map from turning into an EnrollmentApi by accident.
explicit EnrollmentApi(std::map<std::string, std::string> rows) : rows_{std::move(rows)} {}
// "GET /courses/CS101" or "POST /enroll student=S1&course=CS101".
// Returns the JSON reply; a stored row that cannot be mapped gives an
// error reply, not an exception.
// It looks at how the request starts and passes the rest to
// get_course or post_enroll. Replies it makes itself: unknown_request
// for any other text, and stored_row_invalid when mapping::to_domain
// throws std::runtime_error. The other error replies come from the
// two private functions.
std::string handle(std::string_view request);
// The table, for printing and tests: a const reference, so callers can
// read every row but cannot change one.
const std::map<std::string, std::string>& rows() const { return rows_; }
private:
// Read only (const): a GET never changes the table.
std::string get_course(std::string_view code) const;
// May rewrite one row, but only when the enrollment changed the course.
std::string post_enroll(std::string_view query);
std::map<std::string, std::string> rows_; // the table: code -> row
};

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

enrollment_api.cpp
// "POST /enroll student=S2&course=CS101" after handle has cut off the
// prefix: query is "student=S2&course=CS101". One request goes through
// every boundary in turn, and each early return leaves the table as it
// was. Replies bad_request, not_found, stored_row_unreadable, or the
// enroll result; a row that breaks a rule makes to_domain throw, which
// handle turns into stored_row_invalid.
std::string EnrollmentApi::post_enroll(std::string_view query) {
// Wire -> request DTO.
// Empty optional when student= or course= is missing.
const std::optional<api::EnrollRequest> request = api::parse_enroll_request(query);
if (!request) return error("bad_request");
// Request DTO -> domain values.
// request->student reads a field through the optional. parse refuses
// text such as "s4" that is not a student id, again with an empty
// optional: a bad request is expected now and then, so it is a value.
const std::optional<domain::StudentId> student = domain::StudentId::parse(request->student);
if (!student) return error("bad_request");
// The course text is the table's key. `const auto row` makes the
// iterator itself fixed, but this function is not const, so the row it
// points at can still be replaced below.
const auto row = rows_.find(request->course);
if (row == rows_.end()) return error("not_found");
// Row -> record -> domain object; the domain decides.
const std::optional<persistence::CourseRecord> record = persistence::read_row(row->second);
if (!record) return error("stored_row_unreadable");
// A fresh Course, owned by this function. It is a working copy: the
// table only changes if the row is written back below.
domain::Course course = mapping::to_domain(*record);
// The rule lives in Course::enroll: seated, waitlisted, or
// already_in_course. The application does not check seats itself.
const domain::JoinResult result = course.enroll(*student);
if (result == domain::JoinResult::already_in_course) {
return api::to_json(mapping::to_reply(result, course)); // nothing changed, nothing written
}
// Domain object -> record -> row, written in the current version.
// Assigning to row->second replaces the text stored in the map, so a
// version 1 row comes back as version 2 ("2|...|S1,S2|").
row->second = persistence::write_row(mapping::to_record(course));
// Result -> reply DTO.
// to_reply runs after enroll, so a waitlisted reply reads the new length.
return api::to_json(mapping::to_reply(result, course));
}
How this code works: One POST request through every shape

The second request in main is POST /enroll student=S2&course=CS101, and the table holds CS101 as the version 1 row 1|CS101|Software Design|2|S1. Here is who calls whom, and what each step holds.

  1. handle (application) sees that the text starts with POST /enroll , and calls post_enroll with the rest, student=S2&course=CS101, inside its try block.
  2. api::parse_enroll_request (API shape) splits the text and returns an EnrollRequest holding the strings "S2" and "CS101". Nothing has been checked yet beyond “both fields are there”.
  3. domain::StudentId::parse("S2") (domain value) accepts the text: S followed by one to six digits. With s4 it would give an empty optional, and the reply would be bad_request.
  4. rows_.find("CS101") finds the row. With PH101 the reply would be not_found.
  5. persistence::read_row (stored shape) sees five fields starting with 1, a version 1 row, and returns a CourseRecord: capacity 2, seated {"S1"}, waiting empty.
  6. mapping::to_domain builds a domain::Course and replays S1 into its one taken seat. This Course is a local variable of post_enroll: the application owns it, only for this request.
  7. course.enroll (the domain decides) finds 1 of 2 seats taken and answers seated.
  8. mapping::to_record and persistence::write_row turn the course back into text, 2|CS101|Software Design|2|S1,S2|, and the assignment to row->second replaces the row in the table: the old row is upgraded to version 2.
  9. mapping::to_reply gives EnrollReply{"seated"}, and api::to_json writes {"status":"seated"}, which is what handle returns.
  10. When post_enroll returns, the local Course and CourseRecord are destroyed. Only the row in rows_ and the JSON reply remain.

The boundary between the API shapes and the domain is crossed in steps 2 and 3, the one between storage and the domain in steps 5, 6, and 8, and every crossing is one named function. The order also decides what a failure leaves behind: each refusal returns before step 8, so nothing is written, and to_domain can only throw in step 6, also before step 8.

Each comment names one crossing: wire to request, request to domain values, row to record to domain object, and back. The application is the one place that sees every shape, because it calls the mapping functions in order; it does not convert anything itself beyond parsing one id. The course text is used directly as the table’s key, so an unknown or badly formed code gives not_found. A row that read_row cannot read gives stored_row_unreadable. A record that cannot be turned into a Course makes to_domain throw; handle catches that and replies stored_row_invalid, so a bad row does not end the program.

The two kinds of failure are reported differently on purpose. A bad request is expected now and then, so parsing it gives a std::optional, checked on the spot. A stored row that breaks the rules means the data is corrupt, which should not happen, so it is an exception, caught once at the top. The errors and contracts page explains that choice.

A refused enrollment returns before the row is written, so the row is left as it was, in whatever version it had.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

enrollment_api.cpp
// "GET /courses/CS101" after handle has cut off the prefix: code is
// "CS101". Replies not_found, stored_row_unreadable, or the course view as
// JSON. If the row is readable but breaks a rule, to_domain throws, and the
// exception leaves this function; handle catches it and replies
// stored_row_invalid. Nothing is written: a GET only reads.
std::string EnrollmentApi::get_course(std::string_view code) const {
// find looks the code up as a key and gives an iterator (a pointer-like
// handle) to the entry, or rows_.end() if there is none. The map's key
// type is std::string, so the view is copied into one for the lookup.
// The code text is used as is: "cs101" or "PH101" is simply not found.
const auto row = rows_.find(std::string{code});
if (row == rows_.end()) return error("not_found");
// row->second is the stored row text (row->first is the key).
const std::optional<persistence::CourseRecord> record = persistence::read_row(row->second);
if (!record) return error("stored_row_unreadable");
// Read inside out: *record takes the record out of the optional,
// to_domain rebuilds the Course (and may throw), to_view keeps only the
// counts, and to_json writes the view. The Course is a temporary that
// is destroyed at the end of this line.
// row -> record -> domain -> view: the client never sees the row or the ids.
return api::to_json(mapping::to_view(mapping::to_domain(*record)));
}

The table starts as an older program left it: CS101 is a version 1 row.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

main.cpp
int main() {
// The table as an older version of the program left it: CS101 was
// written before waitlists existed, in version 1 of the row format.
// The outer braces call the constructor; the inner ones build the
// std::map from {key, row} pairs. MA101 has empty seated and waiting
// fields, hence the "||" at the end.
app::EnrollmentApi api{{
{"CS101", "1|CS101|Software Design|2|S1"},
{"MA101", "2|MA101|Linear Algebra|30||"},
}};
// The requests to send, in order: a plain array of string_views. Each
// points at a string literal, which lasts for the whole program, so
// the array can be constexpr (fixed when the program is compiled).
constexpr std::string_view requests[] = {
"GET /courses/CS101",
"POST /enroll student=S2&course=CS101",
"POST /enroll student=S3&course=CS101",
"POST /enroll student=S3&course=CS101",
"POST /enroll student=S4",
"POST /enroll student=s4&course=CS101",
"POST /enroll student=S4&course=PH101",
"GET /courses/CS101",
};
// Each request goes through handle, the one entry point, and its reply
// is printed under it. The api object keeps its table between calls,
// so later requests see the rows that earlier ones wrote.
for (const std::string_view request : requests) {
std::cout << "> " << request << '\n' << api.handle(request) << '\n';
}
std::cout << "--- stored rows ---\n";
// Each map entry is a key/value pair; `const auto& [code, row]` names
// its two halves (a structured binding). A std::map keeps its keys
// sorted, so CS101 prints before MA101. Only the row is printed.
for (const auto& [code, row] : api.rows()) std::cout << row << '\n';
}
Expected output
> GET /courses/CS101
{"code":"CS101","title":"Software Design","capacity":2,"seats_taken":1,"waiting":0}
> POST /enroll student=S2&course=CS101
{"status":"seated"}
> POST /enroll student=S3&course=CS101
{"status":"waitlisted","position":1}
> POST /enroll student=S3&course=CS101
{"status":"already_in_course"}
> POST /enroll student=S4
{"status":"bad_request"}
> POST /enroll student=s4&course=CS101
{"status":"bad_request"}
> POST /enroll student=S4&course=PH101
{"status":"not_found"}
> GET /courses/CS101
{"code":"CS101","title":"Software Design","capacity":2,"seats_taken":2,"waiting":1}
--- stored rows ---
2|CS101|Software Design|2|S1,S2|S3
2|MA101|Linear Algebra|30||

The first request reads the version 1 row and shows it as a view with "waiting":0. The first successful enrollment rewrites CS101 as a version 2 row, as the stored rows at the end show. The views never contain a student id, although the rows do. student=S4 with no course is a bad_request because the request shape is incomplete; student=s4 is a bad_request because the text is not a student id; PH101 is not_found. MA101 was never changed, so its row is still the one the table started with. Which of these checks belongs where is the subject of the next page, on API contracts and validation.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

CMakeLists.txt
# Each shape lives in its own library, so each boundary's code can link
# only the shapes it is allowed to know.
add_library(arch_map_api STATIC api/dto.cpp) # client shapes
target_include_directories(arch_map_api PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/api)
add_library(arch_map_persistence STATIC persistence/record.cpp) # stored shapes
target_include_directories(arch_map_persistence PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/persistence)
# The mapping knows all three shapes; the domain (the aggregate page's
# library, unchanged) knows none of the other two.
add_library(arch_map_mapping STATIC mapping/mapping.cpp)
target_include_directories(arch_map_mapping PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/mapping)
target_link_libraries(arch_map_mapping PUBLIC arch_agg_domain arch_map_api arch_map_persistence)
add_library(arch_map_app STATIC app/enrollment_api.cpp)
target_include_directories(arch_map_app PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/app)
target_link_libraries(arch_map_app PRIVATE arch_map_mapping)
lld_add_example(arch_enrollment_mapping SOURCES main.cpp EXPECTED_OUTPUT expected_output.txt)
target_link_libraries(arch_enrollment_mapping PRIVATE arch_map_app)
lld_add_test(arch_map_record_tests SOURCES tests/test_record.cpp)
target_link_libraries(arch_map_record_tests PRIVATE arch_map_persistence)
lld_add_test(arch_map_mapping_tests SOURCES tests/test_mapping.cpp)
target_link_libraries(arch_map_mapping_tests PRIVATE arch_map_mapping)
lld_add_test(arch_map_api_tests SOURCES tests/test_api.cpp)
target_link_libraries(arch_map_api_tests PRIVATE arch_map_app)

arch_map_api and arch_map_persistence link nothing: in their sources, a plain #include "course.hpp" does not compile, because the domain’s include directory is not on their include path. (A relative path to the file would still work; include paths guide, they do not lock.) The domain library is the DDD page’s, and it knows neither shape. arch_map_mapping links all three. arch_map_app links the mapping privately, so it sees every shape, but code that uses the application does not inherit them. No test here checks the include paths; the clean architecture page shows such a check.

The record, alone: round trips, the old version, and rows in neither format:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_record.cpp
// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure
// if the condition is false. LLD_CHECK_EQ(actual, expected) does the same
// for actual == expected, and on failure also prints both values, so it
// is used for strings and numbers; lists, which cannot be printed, are
// compared with LLD_CHECK. They come from the site's small test header,
// lld_test.hpp. These tests use storage alone: no domain, no API.
// Writes a record, checks the exact row text, then reads it back and
// checks every field. Proves write_row and read_row agree on the format.
LLD_TEST(a_row_round_trips_through_the_record) {
// Fields in declaration order: code, title, capacity, seated, waiting.
const persistence::CourseRecord record{"CS101", "Software Design", 2, {"S1", "S2"}, {"S3"}};
const std::string row = persistence::write_row(record);
LLD_CHECK_EQ(row, std::string{"2|CS101|Software Design|2|S1,S2|S3"});
const auto read = persistence::read_row(row); // a std::optional<CourseRecord>
LLD_CHECK(read.has_value());
// read-> reaches into the optional. If it were empty, this would be
// undefined behaviour; LLD_CHECK records the failure but does not stop
// the test, so these lines trust that has_value() was true.
LLD_CHECK_EQ(read->code, record.code);
LLD_CHECK_EQ(read->title, record.title);
LLD_CHECK_EQ(read->capacity, record.capacity);
LLD_CHECK(read->seated == record.seated && read->waiting == record.waiting);
}
// An old row, five fields and no waitlist, still reads: one seated
// student and an empty waitlist. Proves version 1 rows are not lost.
LLD_TEST(a_version_1_row_reads_with_an_empty_waitlist) {
const auto read = persistence::read_row("1|CS101|Software Design|2|S1");
LLD_CHECK(read.has_value());
// std::size_t{1}, not 1: size() is unsigned, and comparing it with a
// signed int is a warning that this build treats as an error.
LLD_CHECK_EQ(read->seated.size(), std::size_t{1});
LLD_CHECK(read->waiting.empty());
}
// Three rows read_row must refuse with an empty optional: a version it
// does not know, a capacity that is not a number, and a version 2 row
// with only five fields. Proves format errors give no record at all.
LLD_TEST(a_row_in_neither_format_is_refused) {
LLD_CHECK(!persistence::read_row("3|CS101|Software Design|2||").has_value()); // unknown version
LLD_CHECK(!persistence::read_row("2|CS101|Software Design|two||").has_value());
LLD_CHECK(!persistence::read_row("2|CS101|Software Design|2|S1").has_value()); // field missing
}

The mapping: a course survives the trip to a record and back with every field, a record that breaks a rule is refused, the view has counts and no ids, and the reply says where the student went:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_mapping.cpp
// The helpers 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 an exception of that type.
// *domain::CourseCode::parse("CS101") takes the value out of the optional
// that parse returns; the test text is known to be valid, so it is not empty.
// A one-seat course with S1 seated and S2 waiting goes to a record and
// back. Proves no field, seated or waiting, is lost or reordered.
LLD_TEST(a_course_survives_the_trip_to_a_record_and_back) {
domain::Course course{*domain::CourseCode::parse("CS101"), "Software Design", 1};
course.enroll(*domain::StudentId::parse("S1"));
course.enroll(*domain::StudentId::parse("S2"));
const domain::Course back = mapping::to_domain(mapping::to_record(course));
// Every field, so a field a mapping function forgets is caught here.
LLD_CHECK(back.code() == course.code());
LLD_CHECK_EQ(back.title(), course.title());
LLD_CHECK_EQ(back.capacity(), course.capacity());
LLD_CHECK(back.seated() == course.seated());
LLD_CHECK(back.waitlist() == course.waitlist());
}
// Two records the rules could never produce: two students seated in one
// seat, and an id that is not a StudentId. Proves to_domain refuses both
// with std::runtime_error, the type the application catches.
LLD_TEST(a_record_that_breaks_a_rule_is_refused) {
const persistence::CourseRecord crowded{"CS101", "Software Design", 1, {"S1", "S2"}, {}};
LLD_CHECK_THROWS(mapping::to_domain(crowded), std::runtime_error);
const persistence::CourseRecord bad_id{"CS101", "Software Design", 1, {"student1"}, {}};
LLD_CHECK_THROWS(mapping::to_domain(bad_id), std::runtime_error);
}
// S1 seated, S2 waiting. Proves the JSON a client gets has the counts
// 1 and 1, and that neither "S1" nor "S2" appears in it.
LLD_TEST(the_view_has_counts_and_no_ids) {
domain::Course course{*domain::CourseCode::parse("CS101"), "Software Design", 1};
course.enroll(*domain::StudentId::parse("S1"));
course.enroll(*domain::StudentId::parse("S2"));
LLD_CHECK_EQ(api::to_json(mapping::to_view(course)),
// Two string literals side by side are joined into one.
std::string{"{\"code\":\"CS101\",\"title\":\"Software Design\",\"capacity\":1,"
"\"seats_taken\":1,\"waiting\":1}"});
}
// S1 takes the only seat, S2 waits first in line. Proves the replies are
// {"status":"seated"} with no position, and "waitlisted" with position 1.
LLD_TEST(the_reply_says_where_the_student_went) {
domain::Course course{*domain::CourseCode::parse("CS101"), "Software Design", 1};
const domain::JoinResult first = course.enroll(*domain::StudentId::parse("S1"));
const domain::JoinResult second = course.enroll(*domain::StudentId::parse("S2"));
LLD_CHECK_EQ(api::to_json(mapping::to_reply(first, course)), std::string{"{\"status\":\"seated\"}"});
LLD_CHECK_EQ(api::to_json(mapping::to_reply(second, course)),
std::string{"{\"status\":\"waitlisted\",\"position\":1}"});
}

The application: old rows are rewritten in the new version, a refusal leaves the row alone, and a bad stored row gives an error reply:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_api.cpp
// These go through EnrollmentApi::handle, the way a client would, and then
// read the table with rows().at(code), which throws if the key is absent.
// The table holds a version 1 row. S2 is seated, and the row is written
// back as version 2: six fields, S1,S2 seated, an empty waiting field.
LLD_TEST(an_old_row_is_rewritten_in_the_current_version) {
app::EnrollmentApi api{{{"CS101", "1|CS101|Software Design|2|S1"}}};
LLD_CHECK_EQ(api.handle("POST /enroll student=S2&course=CS101"),
std::string{"{\"status\":\"seated\"}"});
LLD_CHECK_EQ(api.rows().at("CS101"), std::string{"2|CS101|Software Design|2|S1,S2|"});
}
// S1 is already seated, and the second request has no student. Proves
// neither request writes: the row is still the original version 1 text.
LLD_TEST(a_refused_request_leaves_the_row_alone) {
app::EnrollmentApi api{{{"CS101", "1|CS101|Software Design|2|S1"}}};
LLD_CHECK_EQ(api.handle("POST /enroll student=S1&course=CS101"),
std::string{"{\"status\":\"already_in_course\"}"});
LLD_CHECK_EQ(api.handle("POST /enroll course=CS101"), std::string{"{\"status\":\"bad_request\"}"});
LLD_CHECK_EQ(api.rows().at("CS101"), std::string{"1|CS101|Software Design|2|S1"});
}
// A well-formed row with two students seated in one seat. read_row accepts
// it, to_domain throws, and handle turns that into an error reply instead
// of letting the exception end the program.
LLD_TEST(a_stored_row_that_breaks_a_rule_gives_an_error_reply) {
app::EnrollmentApi api{{{"CS101", "2|CS101|Software Design|1|S1,S2|"}}};
LLD_CHECK_EQ(api.handle("GET /courses/CS101"), std::string{"{\"status\":\"stored_row_invalid\"}"});
}

The separation is not free. Adding one field, such as a course’s credits, now touches:

Place Change
domain::Course a member, a constructor parameter, a getter
persistence::CourseRecord a field, and a new row version
read_row and write_row the new field, and reading the older version
api::CourseView a field, if clients should see it
to_record, to_domain, to_view one line each
tests the round trip, the old version

One struct would have needed one change. The separate shapes need several, and a field forgotten in one mapping function is silently dropped; a round-trip test that compares every field, like the mapping test above, is what catches that. Each request also copies data between shapes. For a few fields that is cheap; for large collections, map only what the request needs.

In return, the table’s format, the API’s contract, and the domain’s rules can each change without the other two. Whether that is worth these edits per field depends on how often each of them changes on its own.

  • The shapes really are the same, and change together. An internal tool whose only client is the same team, storing exactly what it shows, gains nothing from three copies of one struct.
  • The data has no rules. A settings record that is read, shown, and saved can be one struct; there is no domain object to protect.
  • Read-only reports. A query that reads rows straight into the view struct, skipping the domain object, is simpler and faster; the domain object exists to guard changes, and a report changes nothing.

A reasonable path is to start with fewer shapes and split at the boundary that starts changing for its own reasons: usually the client contract first, when other teams depend on it, and storage when its format must evolve.

  • Rules in a DTO. A request struct that checks capacity, or a view with an enroll function, mixes the boundary with the domain. DTOs carry data; the domain decides.
  • A domain object that knows its formats. Course::to_json() or Course::from_row() makes the domain depend on the API and the storage. Put the functions in the mapping.
  • Mapping that decides. A to_domain that silently drops a student who does not fit hides corrupt data. Refuse instead, as the replay does.
  • Exposing the record through the API. Returning CourseRecord as the JSON reply ties every client to the storage format; the next column rename breaks them.
  • A DTO per class, by habit. A shape that matches another field for field, and always changes with it, is a copy to maintain, not a boundary.
  • Clients want the waitlist position of the asking student. That is a new field on a new view, such as MyEnrollmentView, built by a new mapping function from the course and the student’s id. Course already has the data.
  • Storage moves to a database with a separate seats table. The record splits into CourseRow and SeatRow, and read_row and write_row become database code. The domain and the API do not change.
  • Administrators may see the ids. Add an AdminCourseView with the lists, mapped by its own function, and choose the view by the caller’s role. The ordinary view keeps hiding them.
  • The API needs a second version. Keep CourseView for version 1 and add CourseViewV2; both are mapped from the same Course, so the domain serves both.

Exercise: Decide whether to add a DTO

For each situation, decide whether a separate shape is worth it, and which boundary it would sit on.

  1. A command-line tool for the registrar’s own team reads a list of rooms from a file and prints it. Nobody else uses the file.
  2. A mobile app shows a student’s timetable. The domain’s Course gains fields every term; the app is released twice a year.
  3. The billing service receives a message each time a student is seated. It needs the student id, the course code, and the credits.
  4. A course’s title is shown on the website and stored in the table, with exactly the same text.
Show the explained answer
  1. No. One struct read from the file and printed is enough. There is one audience, no rules, and the format changes with the tool. A second shape would be a copy with nothing to protect.
  2. Yes, a view DTO for the app. The app’s contract must stay stable while Course changes every term. A TimetableView with the fields the app shows lets the domain grow without breaking app versions already installed.
  3. Yes, a message DTO, such as StudentSeatedMessage, built from the StudentSeated domain event plus the course’s credits, which the event does not carry, so the mapping looks them up. Another service depends on it, so it is a contract; it should not be the domain event type itself, which may change with the domain.
  4. No new shape for that. The same text in two shapes is not a reason to merge them, nor to split one. Whether the title gets separate shapes depends on the rest of each shape, as in situations 2 and 3. A field that is the same everywhere is simply copied by the mapping.
  • Clients, the domain, and storage often need different shapes of the same data, because each changes for different reasons.
  • Shapes without rules, DTOs and records, are plain structs with public members. The domain object keeps its data private and guards its invariants.
  • Mapping functions convert one shape into another; they do not decide. Only they, and the code that calls them, know two shapes.
  • By default, rebuild domain objects through their roots, so a bad record is refused, not loaded. When replay is too slow, or today’s rules would refuse yesterday’s valid data, use a restricted factory that checks the invariants on the stored state.
  • A version in the stored record lets a new program read old rows and upgrade them on the next write.
  • A view decides what clients may see, independently of what the domain stores.
  • The separation costs several edits per field and some copying. Use one type when the shapes are the same and change together, when the data has no rules, or for read-only reports.