Layered architecture
What you will learn on this page
Section titled “What you will learn on this page”- The four usual layers, presentation, application, domain, and infrastructure, and what each may know.
- How to build each layer as its own C++ library, so the build refuses an include that breaks the direction.
- Strict and relaxed layering, and where each is worth it.
- How control and data move through the layers, where the testing seams are, and which layer detects each failure.
- The anemic domain model: what goes wrong when the domain layer holds only data.
- The coupling layers leave behind, which the next pages remove.
Four layers
Section titled “Four layers”A layer is a module whose place in a stack says what it may depend on: code in a layer may use the layers below it, never the layers above. The usual four:
| Layer | Responsibility | In the example | Must not |
|---|---|---|---|
| Presentation | Talks to people or other programs: reads input, formats output | presentation::Console |
Decide rules, or reach storage directly |
| Application | One function per use case: finds the data, asks the domain, tells the students | application::EnrollmentService |
Hold business rules of its own, or format replies |
| Domain | The business rules and the objects they protect | domain::Course |
Know about commands, storage, or email |
| Infrastructure | Technical details: storage, email, files, clocks | MemoryStore, MailOutbox |
Decide rules, or call the application |
Each row holds one or more of the module candidates from version 0; infrastructure takes both storage and notifications. Running one request, the candidate that appeared only after the others were separated, became the application layer.
The classic stack, and the one used here
Section titled “The classic stack, and the one used here”The classic picture stacks the layers in the order of the table, each
depending on the one below. That puts infrastructure at the bottom,
so the domain depends on it: a Course might load and save itself
through a database class. The rules then cannot be compiled, or tested,
without the storage code.
This page’s version makes one change. The domain depends on nothing. Infrastructure depends on the domain instead, because it stores domain objects. The application uses both:
Text description of the diagram
A layer diagram with four layers from top to bottom: Presentation (Console), Application (EnrollmentService), Infrastructure (MemoryStore and MailOutbox), and Domain (Course and Student). Presentation uses Application. Application uses Infrastructure and Domain. Infrastructure stores Domain objects. Domain has no outgoing arrows. Outside the stack, main, the composition root, creates the presentation, application, and infrastructure objects and depends on all three; those arrows are dashed.
Diagram source (Mermaid)
flowchart TB
Main["main<br/>composition root"]
P["Presentation<br/>Console"]
A["Application<br/>EnrollmentService"]
I["Infrastructure<br/>MemoryStore, MailOutbox"]
D["Domain<br/>Course, Student"]
P -->|uses| A
A -->|uses| I
A -->|uses| D
I -->|stores| D
Main -.->|creates and depends on| P
Main -.->|creates and depends on| A
Main -.->|creates and depends on| IOne coupling remains, and it is on purpose: the application uses the
concrete MemoryStore and MailOutbox classes. A test of the
application must use them too. Here that is cheap, because both are in
memory, but with a real database it would not be. The page on the
hexagonal architecture removes this coupling with interfaces the
application owns.
Strict and relaxed layering
Section titled “Strict and relaxed layering”- Strict layering: each layer uses only the layer directly below it.
- Relaxed layering: a layer may use any layer below it.
In the example, the presentation layer is strict: the console calls only the application, never the domain or the store. The application layer is relaxed: it uses both infrastructure and the domain below it.
Strictness has a cost. If the application could reach the domain
only through infrastructure, MemoryStore would need a function for
every Course operation that does nothing but forward the call. Strictness also has a benefit: the presentation layer cannot
skip the use cases, so it cannot change a course without the
notifications being sent.
A useful rule: be strict where skipping a layer would skip a rule,
and relaxed where it would only skip a forwarding function. A console
that reads MemoryStore directly to print a report skips nothing
today, but the day a report must hide students who asked not to be
listed, that rule is in the application, and the console misses it.
The code, layer by layer
Section titled “The code, layer by layer”The example has one directory and one library per layer. Here are the classes, from the bottom up:
class domain::Course
domain: the rules; depends on nothing
Data members
CourseCode code_;std::string title_;int capacity_;at least 1std::vector<StudentId> seated_;size() <= capacity_std::deque<StudentId> waitlist_;first in line first
Member functions
EnrollOutcome enroll(const StudentId& student);DropOutcome drop(const StudentId& student);static bool is_valid_capacity(int capacity);
class infrastructure::MemoryStore
infrastructure: stands in for a database
Data members
std::map<CourseCode, domain::Course> courses_;ownedstd::map<StudentId, domain::Student> students_;owned
Member functions
domain::Course* find_course(const CourseCode& code);null if noneconst domain::Student* find_student(const StudentId& id) const;
class infrastructure::MailOutbox
infrastructure: stands in for an email gateway
Data members
std::ostream* out_;non-owning, never null
Member functions
void send(const StudentId& to, std::string_view text);
class application::EnrollmentService
application: one function per use case
Data members
infrastructure::MemoryStore* store_;non-owning, never nullinfrastructure::MailOutbox* mail_;non-owning, never null
Member functions
EnrollResult enroll(const std::string& student, const std::string& course);DropResult drop(const std::string& student, const std::string& course);std::optional<CourseReport> report(const std::string& course) const;
class presentation::Console
presentation: text in, text out
Data members
application::EnrollmentService* service_;non-owning, never null
Member functions
std::string run(std::string_view line);
Domain: the rules, and nothing else
Section titled “Domain: the rules, and nothing else”Course keeps every enrollment rule: the capacity, no student listed
twice, and the first student waiting gets a freed seat. Its results
say what happened, in the domain’s own words:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// What Course::enroll did, as plain data instead of a reply sentence. The// domain reports the result; the presentation layer decides the wording.// Kind names the four possible results; `position` matters only for// `waitlisted` and is 0 otherwise. The `= ...` after each member is its// default value, so `EnrollOutcome{}` is always fully set.struct EnrollOutcome { enum class Kind { seated, waitlisted, already_seated, already_waitlisted }; Kind kind = Kind::seated; std::size_t position = 0; // place on the waitlist, from 1, when waitlisted};
// What Course::drop did. `promoted` is a std::optional: it holds a student// id only when the drop freed a seat and someone moved up from the// waitlist, and is empty (std::nullopt) in every other case.struct DropOutcome { enum class Kind { left_seat, left_waitlist, not_in_course }; Kind kind = Kind::not_in_course; std::optional<StudentId> promoted; // who took the freed seat, if anyone};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A course with limited seats and a first-come waitlist. It keeps its// own rules: never more seated students than seats, nobody listed twice,// and a freed seat goes to the first student waiting. It knows nothing// about commands, storage, or email.class Course {public: // Static, so a caller can check a capacity before trying to build a // Course (the service does, to refuse with a reply instead of throwing). static bool is_valid_capacity(int capacity) { return capacity >= 1; }
// Throws std::invalid_argument unless is_valid_capacity(capacity). // code and title are taken by value and moved into the members. Course(CourseCode code, std::string title, int capacity);
// The two rules. Neither throws for an ordinary refusal such as "already // enrolled": each returns an outcome saying what happened, and a refusal // leaves the course unchanged. EnrollOutcome enroll(const StudentId& student); DropOutcome drop(const StudentId& student);
// Read-only views of the state. The strings and lists come back as const // references, so the caller sees the real list without copying it and cannot change it: // only enroll and drop change a Course. const CourseCode& code() const { return code_; } const std::string& title() const { return title_; } int capacity() const { return capacity_; } const std::vector<StudentId>& seated() const { return seated_; } const std::deque<StudentId>& waitlist() const { return waitlist_; }
private: CourseCode code_; std::string title_; int capacity_; std::vector<StudentId> seated_; // in enrollment order; size() <= capacity_ std::deque<StudentId> waitlist_; // first in line first; empty while seats are free};The rules themselves are the same checks as in version 0’s enroll
and drop, without the parsing, the lookups, and the email:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The enrollment rule. Input: a student id; the course does not check that// the student exists (the service does that). Result: an outcome saying// what happened. The order of checks matters: duplicates are refused first,// so a student can never be listed twice, and only then is a free seat or// the waitlist chosen. The two refusals return before any change.EnrollOutcome Course::enroll(const StudentId& student) { // std::ranges::find scans the list from the front and returns an // iterator to the first match, or end() if there is none. if (std::ranges::find(seated_, student) != seated_.end()) { // `return {kind, 0};` builds an EnrollOutcome from a brace list, in // the order its members are declared: kind, then position. return {EnrollOutcome::Kind::already_seated, 0}; } if (std::ranges::find(waitlist_, student) != waitlist_.end()) { return {EnrollOutcome::Kind::already_waitlisted, 0}; } // std::ssize returns a signed size, so it compares cleanly with the int // capacity_. A free seat means the waitlist is empty, so taking the seat // cannot jump ahead of anyone who is waiting. if (std::ssize(seated_) < capacity_) { seated_.push_back(student); // copies the id into the course return {EnrollOutcome::Kind::seated, 0}; } // Full: join the back of the line. The new length is this student's // position, counted from 1. waitlist_.push_back(student); return {EnrollOutcome::Kind::waitlisted, waitlist_.size()};}
// The drop rule. A seated student gives up their seat, and the first// student waiting (if any) takes it; a waiting student just leaves the// line; anyone else gets not_in_course and nothing changes. Students// behind a student who leaves the waitlist move up one place, because// erase closes the gap. The course only reports what changed; telling// anyone is the service's job.DropOutcome Course::drop(const StudentId& student) { // `if (init; condition)`: `seat` is the search result, and it exists // only inside this if, which is the only place it is needed. if (const auto seat = std::ranges::find(seated_, student); seat != seated_.end()) { // erase removes that one id; the iterator `seat` is not used again, // which matters because erase invalidates it. seated_.erase(seat); if (waitlist_.empty()) return {DropOutcome::Kind::left_seat, std::nullopt}; // Moving the id cannot throw, and the vector has room after the // erase, so the seat and the waitlist change together. // std::move hands the id string over instead of copying it; the // emptied string at the front is then removed with pop_front. seated_.push_back(std::move(waitlist_.front())); waitlist_.pop_front(); // seated_.back() is the promoted student, just added; the return // copies the id into the outcome's optional. return {DropOutcome::Kind::left_seat, seated_.back()}; } if (const auto place = std::ranges::find(waitlist_, student); place != waitlist_.end()) { waitlist_.erase(place); return {DropOutcome::Kind::left_waitlist, std::nullopt}; } return {DropOutcome::Kind::not_in_course, std::nullopt};}How this code works: Course::drop, traced with the script's values
drop asks one question at a time and stops at the first “yes”.
- Is the student seated? If so,
eraseremoves them fromseated_. If nobody is waiting, that is all:left_seat, with no one promoted. Otherwise the first id inwaitlist_is moved to the back ofseated_, removed from the front of the waitlist, and returned inpromoted. - Is the student waiting? If so, they are erased from the waitlist, and everyone behind them moves up one place.
- Neither.
not_in_course, and nothing changed.
In the script, CS101 has 2 seats, and after the six enroll commands it holds:
| Call | seated_ before |
waitlist_ before |
Outcome | seated_ after |
waitlist_ after |
|---|---|---|---|---|---|
drop("S1") |
S1, S2 | S3, S4 | left_seat, promoted S3 |
S2, S3 | S4 |
drop("S4") |
S2, S3 | S4 | left_waitlist |
S2, S3 | empty |
After each call the invariants still hold: never more than 2 seated, nobody listed twice, and nobody waiting while a seat is free. The course only returns the outcome; it is the service, a layer up, that turns “promoted S3” into a notification.
The invariant seated_.size() <= capacity_ cannot be broken from
outside: the only functions that change the lists are enroll and
drop, and both keep it. The constructor refuses a capacity below 1.
Infrastructure: storage and email stand-ins
Section titled “Infrastructure: storage and email stand-ins”MemoryStore keeps the courses and students in maps, standing in for
a database. It owns the objects and hands out pointers, which stay
valid because std::map never moves its elements and the store has
no function that erases one:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Keeps courses and students in memory; it stands in for a database.// The application uses this concrete class directly: that is the// coupling the hexagonal architecture page removes.class MemoryStore {public: // Each returns false, and stores nothing, if the code or id is taken. // The parameter is taken by value: the caller's object is copied or // moved in, and the store then moves it into its map, so the store // owns its own copy of every course and student. bool add_course(domain::Course course); bool add_student(domain::Student student);
// Null if there is none. A pointer stays valid until the store is // destroyed: std::map never moves its elements. Returning a pointer // (not a copy) is what lets the service change the stored course. // nullptr is how "not found" is said here, so every caller must check. // There are two find_course functions: a non-const one that gives a // changeable Course, for enroll and drop, and a const one that gives a // read-only Course, chosen when the store is used as const (report asks // for it with std::as_const). domain::Course* find_course(const domain::CourseCode& code); const domain::Course* find_course(const domain::CourseCode& code) const; const domain::Student* find_student(const domain::StudentId& id) const;
private: // The store owns the data by value, keyed by code and by id. std::map<domain::CourseCode, domain::Course> courses_; std::map<domain::StudentId, domain::Student> students_;};MailOutbox stands in for an email gateway. It borrows the stream
from main:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Sends notifications; it stands in for an email gateway and writes// each message as one line.class MailOutbox {public: // `out` must outlive the outbox. The constructor takes a reference (so // a null stream cannot be passed) and stores its address, &out. explicit MailOutbox(std::ostream& out) : out_{&out} {}
// Writes "notify <id>: <text>" and a newline to the stream. It returns // nothing and does not check the stream for errors; a real email // gateway could fail or be slow, and the service would then have to decide what to do. void send(const domain::StudentId& to, std::string_view text);
private: std::ostream* out_; // non-owning, never null; a pointer keeps the class assignable};Application: one function per use case
Section titled “Application: one function per use case”The application’s header defines its own result types. The presentation layer reads these, so it never needs a domain type:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Results are in the application's own terms, so the presentation layer// never needs a domain type. Each use case returns one of these plain// values, and the console turns it into a sentence. They also add the// cases the domain cannot know about, such as no_such_student: a Course// only sees ids, while the service is the one that looks students up.enum class AddCourseResult { added, already_exists, invalid_capacity };enum class AddStudentResult { added, already_exists };
enum class EnrollStatus { seated, waitlisted, already_seated, already_waitlisted, no_such_student, no_such_course,};// The status plus the one extra fact a reply needs: the waitlist position.struct EnrollResult { EnrollStatus status = EnrollStatus::no_such_course; std::size_t position = 0; // place on the waitlist, from 1, when waitlisted};
enum class DropStatus { left_seat, left_waitlist, not_in_course, no_such_course };struct DropResult { DropStatus status = DropStatus::no_such_course; std::optional<std::string> promoted; // who took the freed seat, if anyone};
// What a "report" shows. These are copies of the data (plain strings and// ints), not pointers into the store, so the caller can keep them as long// as it likes and cannot change a course through them.struct StudentLine { std::string id; std::string name;};
struct CourseReport { std::string code; std::string title; int capacity = 0; std::vector<StudentLine> seated; std::vector<StudentLine> waitlist;};The service only declares the infrastructure classes, at the top of its header, and holds pointers to them. That small choice matters for the build, as the next section shows.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// One public function per use case. Each finds what it needs, lets the// domain decide, and tells the students; it holds no rules of its own.class EnrollmentService {public: // The store and the outbox must outlive the service. It borrows both: // main creates them, and the service only keeps their addresses. EnrollmentService(infrastructure::MemoryStore& store, infrastructure::MailOutbox& mail);
// The use cases. None of them throws for a refusal; the result says why. // report returns an empty std::optional when there is no such course. AddCourseResult add_course(const std::string& code, int capacity, const std::string& title); AddStudentResult add_student(const std::string& id, const std::string& name); EnrollResult enroll(const std::string& student, const std::string& course); DropResult drop(const std::string& student, const std::string& course); std::optional<CourseReport> report(const std::string& course) const;
private: // Pointers to the classes that are only declared above. A pointer to a // declared-but-not-defined class is allowed, which is why this header // does not need to include the infrastructure headers. infrastructure::MemoryStore* store_; // non-owning, never null infrastructure::MailOutbox* mail_; // non-owning, never null};enroll is the version 0 function with the rules taken out. It finds
the student and the course, lets the course decide, and sends the
notification that matches the outcome:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The enroll use case, in three steps: find what is needed in the store,// let the Course apply its rule, then act on the outcome (send mail and// translate the domain outcome into an application result). There is no// seat counting here; that rule lives only in domain::Course::enroll.EnrollResult EnrollmentService::enroll(const std::string& student, const std::string& course) { // 1. Find. Unknown student or course: refuse before anything changes. if (store_->find_student(student) == nullptr) return {EnrollStatus::no_such_student, 0}; // A pointer to the Course inside the store, not a copy: the enroll call // below changes the stored course itself. domain::Course* found = store_->find_course(course); if (found == nullptr) return {EnrollStatus::no_such_course, 0};
// 2. Decide. The domain changes the course (or refuses) and reports which. const domain::EnrollOutcome outcome = found->enroll(student); // the domain decides // 3. Act. Only the two "got a place" outcomes send mail. Each case maps a // domain Kind to the matching application EnrollStatus and returns. switch (outcome.kind) { case domain::EnrollOutcome::Kind::seated: // *found turns the pointer back into the Course it points to. mail_->send(student, "you have a seat in " + course_name(*found)); return {EnrollStatus::seated, 0}; case domain::EnrollOutcome::Kind::waitlisted: mail_->send(student, "you are number " + std::to_string(outcome.position) + " on the waitlist for " + course_name(*found)); return {EnrollStatus::waitlisted, outcome.position}; case domain::EnrollOutcome::Kind::already_seated: return {EnrollStatus::already_seated, 0}; case domain::EnrollOutcome::Kind::already_waitlisted: return {EnrollStatus::already_waitlisted, 0}; } // Every case above returns, so control only gets here if outcome.kind held // a value outside the enum. The line keeps the compiler from warning that // the function might end without returning a value. return {EnrollStatus::no_such_course, 0}; // not reached: every kind is handled above}How this code works: One enroll request through the four layers
Follow enroll S3 CS101 from the script, when both seats are taken.
main(composition root) passes the line toconsole.run.mainowns the store, the outbox, the service, and the console as local objects; every other object only borrows.- Presentation.
Console::runsplits the line into words and calls theenrollfunction inconsole.cpp, which checks there are three words and callsservice.enroll("S3", "CS101"). This is the boundary between text and use cases: only strings cross it, and the console never sees adomain::Course. - Application.
EnrollmentService::enrollasks the store for the student and the course.find_coursereturns a pointer into the store’s map, so no course is copied. - Infrastructure (lookup).
MemoryStorefinds both and returns the pointers. The store keeps owning theCourse; the service only holds a pointer to it for the rest of this call. - Domain. The service calls
found->enroll("S3"). The course finds two students seated out of two seats, pushes S3 onto its waitlist, and returns{waitlisted, 1}. This is the only place that counts seats. - Application again. The
switchpicks thewaitlistedcase, asks the outbox to send"you are number 1 on the waitlist for CS101 Software Design", and returns{EnrollStatus::waitlisted, 1}. - Infrastructure (mail).
MailOutbox::sendwrites thenotify S3: ...line tostd::cout. - Presentation again. The console turns the result into
ok: S3 waitlisted for CS101 (position 1), andmainprints it.
Each call goes down a layer and each result comes back up: the
domain never calls the service, and the service never builds reply
text. Notice also that the service calls two concrete infrastructure
classes, MemoryStore and MailOutbox, directly; that coupling is what
the hexagonal page removes.
The application decides that a student is told and what the
message says. It does not decide how it is delivered; that is the
outbox. The function ends with a return after the switch because
GCC warns, under -Wreturn-type, that control could reach the end of
the function: an enum class variable can hold values that are not
listed. (Clang does not warn for a switch that lists every
enumerator.)
Presentation: text in, text out
Section titled “Presentation: text in, text out”The console turns a line into one call and a result into a reply. It
checks only what only it can know, such as whether 2x is a whole
number:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The presentation half of "enroll": a free function in this file, called// by Console::run when the first word is "enroll". It only parses the// words, makes one call into the application layer, and turns the// EnrollResult into the reply text. Compare it with version 0's enroll:// the same replies, but no lookups and no rules here. `Words` is this// file's short name for std::vector<std::string>.std::string enroll(EnrollmentService& service, const Words& words) { if (words.size() != 3) return "refused: usage: enroll <student> <course>"; const std::string& student = words[1]; const std::string& code = words[2]; // The one call that crosses into the application layer. const application::EnrollResult result = service.enroll(student, code); // Lets the cases below say EnrollStatus::seated instead of // application::EnrollStatus::seated, inside this function only. using application::EnrollStatus; // One reply per status. Every case returns, so none falls through. switch (result.status) { case EnrollStatus::seated: return "ok: " + student + " enrolled in " + code; case EnrollStatus::waitlisted: return "ok: " + student + " waitlisted for " + code + " (position " + std::to_string(result.position) + ")"; case EnrollStatus::already_seated: return "refused: " + student + " is already enrolled in " + code; case EnrollStatus::already_waitlisted: return "refused: " + student + " is already on the waitlist for " + code; case EnrollStatus::no_such_student: return "refused: no student " + student; case EnrollStatus::no_such_course: return "refused: no course " + code; } return "refused: no course " + code; // not reached}The composition root
Section titled “The composition root”main is the only code that sees every layer. It creates the objects
from the bottom up, so each one exists before anything that borrows
it, and they are destroyed in the reverse order:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
int main() { // The same script as version 0; the output must be the same text. constexpr std::string_view script[] = { "course CS101 2 Software Design", "student S1 Ada Lovelace", "student S2 Grace Hopper", "student S3 Alan Turing", "student S4 Barbara Liskov", "enroll S1 CS101", "enroll S2 CS101", "enroll S3 CS101", "enroll S4 CS101", "enroll S3 CS101", "enroll S9 CS101", "drop S1 CS101", "report CS101", "drop S4 CS101", "enroll S1 CS999", "report CS101", };
// main is the only code that sees every layer: it creates the // objects from the bottom up and connects them. // All four are plain local objects, so main owns them and nothing is // allocated with new. Each object is created after the ones it borrows, // which is what makes the "must outlive" rules hold. infrastructure::MemoryStore store; // owns the courses and students infrastructure::MailOutbox mail{std::cout}; // borrows std::cout application::EnrollmentService service{store, mail}; // borrows store and mail presentation::Console console{service}; // borrows service
for (const std::string_view line : script) { std::cout << "> " << line << '\n'; const std::string reply = console.run(line); // may print notifications first std::cout << reply << '\n'; }} // destroyed in reverse: console, service, mail, storeEvery borrowed pointer in the layers points to an object main created
earlier in the same scope, or to std::cout, which outlives main, so
every borrower is destroyed before what
it borrows. The dependency injection
page covers this rule in general.
Making the build enforce the direction
Section titled “Making the build enforce the direction”A layer rule written only in a document is broken the first time it is in the way. The example puts each layer in its own library, and gives each library an include directory that only the layers allowed to use it can see:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
# One library per layer. Each layer's headers are visible only to the# layers allowed to use it; a forbidden #include fails to compile.add_library(arch_layered_domain STATIC domain/course.cpp)target_include_directories(arch_layered_domain PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/domain)
add_library(arch_layered_infrastructure STATIC infrastructure/memory_store.cpp infrastructure/mail_outbox.cpp)target_include_directories(arch_layered_infrastructure PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/infrastructure)target_link_libraries(arch_layered_infrastructure PUBLIC arch_layered_domain)
# PRIVATE: the application's header exposes neither layer below it.add_library(arch_layered_application STATIC application/enrollment_service.cpp)target_include_directories(arch_layered_application PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/application)target_link_libraries(arch_layered_application PRIVATE arch_layered_domain arch_layered_infrastructure)
add_library(arch_layered_presentation STATIC presentation/console.cpp)target_include_directories(arch_layered_presentation PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/presentation)target_link_libraries(arch_layered_presentation PUBLIC arch_layered_application)
# main is the composition root, so it links every layer it creates.lld_add_example(arch_enrollment_layered SOURCES main.cpp EXPECTED_OUTPUT expected_output.txt)target_link_libraries(arch_enrollment_layered PRIVATE arch_layered_presentation arch_layered_application arch_layered_infrastructure)
lld_add_test(arch_layered_domain_tests SOURCES test_domain.cpp)target_link_libraries(arch_layered_domain_tests PRIVATE arch_layered_domain)
lld_add_test(arch_layered_application_tests SOURCES test_application.cpp)target_link_libraries(arch_layered_application_tests PRIVATE arch_layered_application arch_layered_infrastructure)
lld_add_test(arch_layered_console_tests SOURCES test_console.cpp)target_link_libraries(arch_layered_console_tests PRIVATE arch_layered_presentation arch_layered_application arch_layered_infrastructure)
add_library(arch_layered_anemic STATIC anemic/anemic_course.cpp)target_include_directories(arch_layered_anemic PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/anemic)lld_add_test(arch_layered_anemic_tests SOURCES test_anemic.cpp)target_link_libraries(arch_layered_anemic_tests PRIVATE arch_layered_anemic arch_layered_domain)What this enforces:
- The domain sees only itself. Its library links nothing, so
#include "memory_store.hpp"incourse.cppfails to compile. - The presentation layer sees only the application. The
application links the lower layers
PRIVATE, so their include directories do not pass up to its users. That works only because the application’s header declaresMemoryStoreandMailOutboxinstead of including their headers. A scratch file that includesmemory_store.hppwith only the presentation target’s include directories fails with “No such file or directory”. - Infrastructure sees only the domain, because it links only the domain library, so it cannot include application or presentation headers.
- The domain tests link only the domain library, which shows that the rules compile and run without anything else.
PRIVATE stops include directories, not linking. For static libraries
CMake still passes the lower libraries to the final link, which is why
the executable links. main and the tests list infrastructure
themselves because they include its headers.
What it does not enforce:
- An include by relative path, such as
#include "../infrastructure/memory_store.hpp", bypasses include directories. A review rule, or a script that rejects..in includes, closes that gap. - Anyone can edit the
CMakeLists.txtand changePRIVATEtoPUBLIC. The build is a guard, not a lock. - A domain header that no domain
.cppfile includes is compiled only in targets that can see more, so a bad include in it goes unnoticed. The modular monolith page covers stronger checks.
Same behaviour, different structure
Section titled “Same behaviour, different structure”The layered program runs the same script as version 0:
> course CS101 2 Software Designok: course CS101 added> student S1 Ada Lovelaceok: student S1 added> student S2 Grace Hopperok: student S2 added> student S3 Alan Turingok: student S3 added> student S4 Barbara Liskovok: student S4 added> enroll S1 CS101notify S1: you have a seat in CS101 Software Designok: S1 enrolled in CS101> enroll S2 CS101notify S2: you have a seat in CS101 Software Designok: S2 enrolled in CS101> enroll S3 CS101notify S3: you are number 1 on the waitlist for CS101 Software Designok: S3 waitlisted for CS101 (position 1)> enroll S4 CS101notify S4: you are number 2 on the waitlist for CS101 Software Designok: S4 waitlisted for CS101 (position 2)> enroll S3 CS101refused: S3 is already on the waitlist for CS101> enroll S9 CS101refused: no student S9> drop S1 CS101notify S3: a seat opened; you are enrolled in CS101 Software Designok: S1 dropped CS101; S3 moved from the waitlist> report CS101ok: CS101 Software Design, 2/2 seats taken seated: S2 Grace Hopper, S3 Alan Turing waitlist: S4 Barbara Liskov> drop S4 CS101ok: S4 left the waitlist for CS101> enroll S1 CS999refused: no course CS999> report CS101ok: CS101 Software Design, 2/2 seats taken seated: S2 Grace Hopper, S3 Alan Turing waitlist: (none)The build has a test, arch_enrollment_same_output, that compares this
expected output with version 0’s and fails if they differ. The
restructuring changed where the code lives, not what the program does.
Control and data flow
Section titled “Control and data flow”A dependency diagram says who may know whom. This sequence diagram
shows what happens at run time for enroll S3 CS101 when the course
is full:
Text description of the diagram
A sequence diagram for one enroll command. The Console calls EnrollmentService enroll with S3 and CS101. The service asks the MemoryStore for student S3 and course CS101 and gets both. It calls enroll S3 on the Course, which answers waitlisted, position 1. The service asks the MailOutbox to send S3 the waitlist message, then returns an EnrollResult of waitlisted, position 1 to the Console, which formats the reply “ok: S3 waitlisted for CS101 (position 1)”.
Diagram source (Mermaid)
sequenceDiagram
participant C as Console
participant S as EnrollmentService
participant St as MemoryStore
participant Co as Course
participant M as MailOutbox
C->>S: enroll("S3", "CS101")
S->>St: find_student("S3")
St-->>S: the student
S->>St: find_course("CS101")
St-->>S: the course
S->>Co: enroll("S3")
Co-->>S: waitlisted, position 1
S->>M: send("S3", waitlist message)
S-->>C: EnrollResult waitlisted, 1
Note over C: formats "ok: S3 waitlisted..."Control goes down, one layer at a time. Data comes back up as
results, changing type at each boundary: an EnrollOutcome from the
domain, an EnrollResult from the application, and a reply string
from the presentation layer. Each layer translates into the language
of the layer above, so a renamed field or a changed representation
stops at the next boundary. A new outcome still has to be handled in
the layer above.
Testing seams
Section titled “Testing seams”Each layer can be tested at its own boundary. The domain needs nothing else:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The domain is tested on its own: no store, no outbox, no text.// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure// if the condition is false; LLD_CHECK_EQ(actual, expected) records one// if the two are not equal (==) and prints both; LLD_CHECK_THROWS(expression,// type) fails unless the expression throws that type of exception. They// come from the site's small test header, lld_test.hpp.// The `using` lines let the tests write Course instead of domain::Course.using domain::Course;using domain::DropOutcome;using domain::EnrollOutcome;
// One seat: S1 takes it, then S2 and S3 queue. Proves the outcome kinds// and that waitlist positions count from 1 in arrival order. The expected// values are written std::size_t{1} so both sides of the comparison have// the same unsigned type as `position`.LLD_TEST(a_full_course_waitlists_in_arrival_order) { Course course{"CS101", "Software Design", 1}; LLD_CHECK(course.enroll("S1").kind == EnrollOutcome::Kind::seated); const EnrollOutcome second = course.enroll("S2"); LLD_CHECK(second.kind == EnrollOutcome::Kind::waitlisted); LLD_CHECK_EQ(second.position, std::size_t{1}); LLD_CHECK_EQ(course.enroll("S3").position, std::size_t{2});}
// S1 is seated and S2 waits; each then tries again. Proves both repeats// are refused with their own kind and that neither list grew.LLD_TEST(nobody_is_listed_twice) { Course course{"CS101", "Software Design", 1}; course.enroll("S1"); // setup; the outcome is not needed here course.enroll("S2"); LLD_CHECK(course.enroll("S1").kind == EnrollOutcome::Kind::already_seated); LLD_CHECK(course.enroll("S2").kind == EnrollOutcome::Kind::already_waitlisted); LLD_CHECK_EQ(course.seated().size(), std::size_t{1}); LLD_CHECK_EQ(course.waitlist().size(), std::size_t{1});}
// S1 seated, S2 then S3 waiting. Dropping S1 must promote S2 (the first in// line, not S3); dropping S3 just removes them from the waitlist; and// dropping S9, who was never in the course, is reported as not_in_course.LLD_TEST(a_freed_seat_goes_to_the_first_student_waiting) { Course course{"CS101", "Software Design", 1}; course.enroll("S1"); course.enroll("S2"); course.enroll("S3"); const DropOutcome dropped = course.drop("S1"); LLD_CHECK(dropped.kind == DropOutcome::Kind::left_seat); LLD_CHECK(dropped.promoted == std::optional<std::string>{"S2"}); LLD_CHECK(course.drop("S3").kind == DropOutcome::Kind::left_waitlist); LLD_CHECK(course.drop("S9").kind == DropOutcome::Kind::not_in_course); LLD_CHECK(course.waitlist().empty());}
// A capacity of 0 must throw. The extra parentheses around Course{...} are// needed because a macro splits its arguments at commas, and braces do not// protect the commas inside them; parentheses do.LLD_TEST(a_course_needs_at_least_one_seat) { LLD_CHECK_THROWS((Course{"CS101", "Software Design", 0}), std::invalid_argument);}The application is tested through its functions and result types, not through text. It has to use the real infrastructure classes, because it names them:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The application is tested with the real infrastructure classes: here// they are in memory, so that is cheap, but the test cannot choose them.namespace {
// The fixture builds the same stack as main, bottom up, but the outbox// writes into a string stream, `sent`, that the tests read back with// sent.str(). Members are created in the order they are declared, so each// one exists before the next one borrows it. The constructor adds one// course with one seat and two students.struct Office { infrastructure::MemoryStore store; std::ostringstream sent; infrastructure::MailOutbox mail{sent}; application::EnrollmentService service{store, mail};
Office() { service.add_course("CS101", 1, "Software Design"); service.add_student("S1", "Ada Lovelace"); service.add_student("S2", "Grace Hopper"); }};
} // namespace
// S1 takes the only seat and S2 is waitlisted at position 1. Proves the two// results and the exact text of the two notifications the service sent.LLD_TEST(enrolling_tells_the_student_where_they_stand) { Office office; LLD_CHECK(office.service.enroll("S1", "CS101").status == application::EnrollStatus::seated); const application::EnrollResult waiting = office.service.enroll("S2", "CS101"); LLD_CHECK(waiting.status == application::EnrollStatus::waitlisted); LLD_CHECK_EQ(waiting.position, std::size_t{1}); LLD_CHECK_EQ(office.sent.str(), std::string{"notify S1: you have a seat in CS101 Software Design\n" "notify S2: you are number 1 on the waitlist for CS101 " "Software Design\n"});}
// S1 seated, S2 waiting; S1 drops. Proves S2 is promoted, S2 alone is told,// and the report (read through `->`, because it is a std::optional) shows// Grace Hopper, S2's name, in the one seat.LLD_TEST(a_dropped_seat_is_offered_and_the_student_told) { Office office; office.service.enroll("S1", "CS101"); office.service.enroll("S2", "CS101"); office.sent.str(""); // empty the captured mail, so only the drop's mail is checked const application::DropResult dropped = office.service.drop("S1", "CS101"); LLD_CHECK(dropped.status == application::DropStatus::left_seat); LLD_CHECK(dropped.promoted == std::optional<std::string>{"S2"}); LLD_CHECK_EQ(office.sent.str(), std::string{"notify S2: a seat opened; you are enrolled in CS101 Software Design\n"}); const std::optional<application::CourseReport> report = office.service.report("CS101"); LLD_CHECK(report.has_value()); LLD_CHECK_EQ(report->seated.size(), std::size_t{1}); LLD_CHECK_EQ(report->seated[0].name, std::string{"Grace Hopper"});}
// Every refusal the application adds: unknown student, unknown course (for// enroll, drop, and report), a capacity of 0, and a duplicate course code.// The last check proves that none of them sent any mail.LLD_TEST(unknown_students_and_courses_are_refused_without_mail) { Office office; LLD_CHECK(office.service.enroll("S9", "CS101").status == application::EnrollStatus::no_such_student); LLD_CHECK(office.service.enroll("S1", "CS999").status == application::EnrollStatus::no_such_course); LLD_CHECK(office.service.drop("S1", "CS999").status == application::DropStatus::no_such_course); LLD_CHECK(office.service.add_course("CS102", 0, "Empty") == application::AddCourseResult::invalid_capacity); LLD_CHECK(office.service.add_course("CS101", 5, "Again") == application::AddCourseResult::already_exists); LLD_CHECK(!office.service.report("CS999").has_value()); LLD_CHECK(office.sent.str().empty());}The console tests check only what the console does: reading text and writing replies.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The console is tested for what only it does: reading text and// writing replies. The rules were tested a layer down.namespace {
// All four layers, wired as in main, with the mail captured in `sent`.// It starts empty: each test adds what it needs through console commands.struct Office { infrastructure::MemoryStore store; std::ostringstream sent; infrastructure::MailOutbox mail{sent}; application::EnrollmentService service{store, mail}; presentation::Console console{service};};
} // namespace
// Four kinds of bad text: an empty line, an unknown command, a missing// argument, and a capacity that is not a whole number. Each gets its own// reply, and the last check proves no course was created.LLD_TEST(malformed_commands_are_refused_before_the_application_is_called) { Office office; LLD_CHECK_EQ(office.console.run(""), std::string{"refused: empty command"}); LLD_CHECK_EQ(office.console.run("register S1"), std::string{"refused: unknown command register"}); LLD_CHECK_EQ(office.console.run("enroll S1"), std::string{"refused: usage: enroll <student> <course>"}); LLD_CHECK_EQ(office.console.run("course CS101 2x Software Design"), std::string{"refused: capacity must be a whole number of at least 1"}); LLD_CHECK(!office.service.report("CS101").has_value());}
// Sets up a one-seat course and two students through commands, then// proves the console turns each result into exactly version 0's wording.LLD_TEST(results_become_the_same_replies_as_version_0) { Office office; office.console.run("course CS101 1 Software Design"); office.console.run("student S1 Ada Lovelace"); office.console.run("student S2 Grace Hopper"); LLD_CHECK_EQ(office.console.run("enroll S1 CS101"), std::string{"ok: S1 enrolled in CS101"}); LLD_CHECK_EQ(office.console.run("enroll S2 CS101"), std::string{"ok: S2 waitlisted for CS101 (position 1)"}); LLD_CHECK_EQ(office.console.run("report CS101"), std::string{"ok: CS101 Software Design, 1/1 seats taken\n" " seated: S1 Ada Lovelace\n" " waitlist: S2 Grace Hopper"});}Compare version 0, where every rule test went through a command and a reply string. Here a change to the reply wording breaks only the console tests, and a change to a rule breaks only the tests that check that rule, apart from the end-to-end output tests, which break for either, by design.
Failure paths: which layer says no
Section titled “Failure paths: which layer says no”Each refusal is detected by the layer that has the knowledge:
| Failure | Detected in | How |
|---|---|---|
| Empty, unknown, or malformed command | Presentation | Reply refused: ...; the application is not called |
| Capacity text that is not a whole number | Presentation | Only the console sees text |
| Capacity below 1 | Domain rule, asked by the application | Course::is_valid_capacity; the constructor also throws, as a backstop |
| Unknown student (enroll) or course | Application | The store returns null; no_such_student or no_such_course. An unknown student who drops is not_in_course |
| Course or student id already exists | Infrastructure, reported by the application | MemoryStore::add_* returns false, like a database’s unique key; the application returns already_exists |
| Already seated, already waiting, not in the course | Domain | EnrollOutcome or DropOutcome |
Unique ids are a rule, but one that storage enforces best, as a database enforces a unique key. The store only reports that the id is taken; the application decides what that means for the request.
Two failure paths are not handled, and the next pages need them:
- Sending fails after the course changed. If
MailOutbox::sendthrew, the seat change would already be in the store, and the exception would skip the reply. With an in-memory store there is nothing to roll back. With a database, the use case must decide the order: save, then send, and what to do if sending fails. Transaction and persistence boundaries answers this with an outbox, and Event-driven application components builds on it. - Two requests at the same time. The program handles one command at a time. A web form with many users would need the course’s changes to be atomic, which is a transaction question again.
The anemic domain model
Section titled “The anemic domain model”The layers can be drawn correctly and still go wrong in one specific way: the domain layer holds only data, and every rule lives in the application layer’s functions. Martin Fowler named this the anemic domain model. It looks layered, but the rules have no home, so each use case repeats the ones it remembers.
The example includes one, deliberately flawed:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The course is only data. Every rule lives in whichever application// function changes it.// Where it goes wrong: every member is public, so any code that can see a// CourseRecord can push into `seated` directly. Nothing in the type// protects "never more seated than capacity" or "nobody listed twice";// those promises hold only if every function that touches the lists// remembers to check them.struct CourseRecord { std::string code; std::string title; int capacity = 1; std::vector<std::string> seated; std::deque<std::string> waitlist;};
// The enrollment use case checks the rules...// It takes the record by non-const reference and changes it in place.void enroll(CourseRecord& course, const std::string& student);
// ...and a use case added later, moving a student to another section,// repeats none of them.void move_to_section(CourseRecord& from, CourseRecord& to, const std::string& student);VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The same three rules as domain::Course::enroll, but written in a free// function outside the data: refuse duplicates, take a free seat, or join// the waitlist. A refusal simply returns, so the caller cannot tell what// happened. This function on its own is correct.void enroll(CourseRecord& course, const std::string& student) { if (std::ranges::find(course.seated, student) != course.seated.end()) return; if (std::ranges::find(course.waitlist, student) != course.waitlist.end()) return; if (std::ssize(course.seated) < course.capacity) { course.seated.push_back(student); } else { course.waitlist.push_back(student); }}
// FLAWED: the later use case. It edits both lists directly instead of// going through enroll, so none of enroll's checks run.void move_to_section(CourseRecord& from, CourseRecord& to, const std::string& student) { // std::erase (C++20) removes every element equal to `student` from the // vector. If the student was not seated in `from`, it removes nothing, // and the next line still adds them to `to`. It also never promotes // the first student waiting for `from`, so that seat stays empty. std::erase(from.seated, student); // The bug the test shows: `to` may already be full, so this can seat // more students than its capacity, skip ahead of everyone on its // waitlist, or list a student who is already there a second time. to.seated.push_back(student); // forgot the capacity, the waitlist, and duplicates}VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Two one-seat sections, `a` (CS101-A) and `b` (CS101-B). S1 takes the seat// in `a`, and S2 the seat in `b`. Then S1 is moved from `a` to `b`. The// check proves the flaw: `b` now has two seated students and a capacity of// 1. The test passes because the bug is real.LLD_TEST(the_anemic_model_lets_a_later_use_case_break_the_capacity_rule) { anemic::CourseRecord a{"CS101-A", "Software Design", 1, {}, {}}; anemic::CourseRecord b{"CS101-B", "Software Design", 1, {}, {}}; anemic::enroll(a, "S1"); anemic::enroll(b, "S2"); anemic::move_to_section(a, b, "S1"); LLD_CHECK_EQ(b.seated.size(), std::size_t{2}); // two students in one seat}
// The same situation with domain::Course: the one seat in `b` is taken by S2.// Course has no public list to push into, so the only way to add S1 is// enroll, which puts S1 on the waitlist and leaves one student seated.LLD_TEST(the_domain_course_offers_no_way_to_do_that) { domain::Course b{"CS101-B", "Software Design", 1}; b.enroll("S2"); // A move can only use the course's own operations, so the rule holds. LLD_CHECK(b.enroll("S1").kind == domain::EnrollOutcome::Kind::waitlisted); LLD_CHECK_EQ(b.seated().size(), std::size_t{1});}With domain::Course, a move between sections can only call enroll
on the new section and drop on the old one, so the capacity and the
waitlist rules apply whether or not the person writing the move
remembers them.
Signs of an anemic model:
- Domain types that have rules to protect are structs with public
members, or classes whose member functions are only getters and
setters. (
domain::Studentis a plain struct because it has no rules to protect; that is fine.) - Functions in the application layer check rules about one object’s
fields, such as
if (std::ssize(course.seated) < course.capacity). - The same check appears in several use cases.
An anemic model is not always wrong. When the program is mostly storing and showing records, with few rules, a plain struct and a function per use case is simpler. The problem is a program with rules that keeps them outside the objects they protect.
When layers help, and when they do not
Section titled “When layers help, and when they do not”Layers help when:
- There are real rules worth testing alone, as here.
- More than one way in is planned, such as a console and a web form, which must apply the same rules.
- The storage or delivery technology is expected to change.
They do not help when:
- The program is a thin wrapper around storage, with no rules. The application and domain layers would only forward calls.
- The program is small and short-lived. Version 0 is easier to read.
- Every change cuts across all four layers anyway, because the program is organized around features that are each small. The modular monolith page shows grouping by feature first, with layers inside each module where needed.
Common mistakes
Section titled “Common mistakes”- Rules in the application layer. The use case checks the capacity; the domain object only stores it. This is the anemic model above.
- Domain types in the presentation layer. The console reads
Coursedirectly. Then every change toCoursereaches the user interface, and the console can callenrollwithout the notifications. - Infrastructure calling upward.
MemoryStorecalls the application to send email when it saves. The arrow now points up, and the layers form a cycle. - Pass-through layers. Every application function only forwards to one domain function. If that is true of all of them, the layer may not be needed yet, or the rules are in the wrong place.
- A layer rule only in a document. Without the build enforcing it, the first deadline breaks it.
When the requirements change
Section titled “When the requirements change”- Tests must run without the real storage: the application names
MemoryStore, so it cannot be given a fake. Give the application interfaces it owns, such asCourseStore, implemented by infrastructure. That is the hexagonal architecture. - A web form is added: a second presentation layer calls the same
EnrollmentService; the rules and the notifications come with it. - The data must survive a restart: replace
MemoryStorewith a database class. Every use case that changes a course must now also save it, and decide what happens if saving fails. Repository and Unit of Work answer this. - Notifications by email and SMS, without delay: the application records “S3 got a seat” and something else delivers it later. That is Event-driven application components.
Exercise: Find the layer violations
Each snippet below would compile in some version of the example. For each, say which layer it is in, which rule it breaks, and what problem that causes. One snippet breaks no layer rule, and the answer for one depends on who owns the rule.
-
In
Console’s report command:const domain::Course* course = store.find_course(words[1]); -
In
Course::enroll:std::cout << "notify " << student << ": you have a seat\n"; -
In
EnrollmentService::enroll:if (found->seated().size() >= static_cast<std::size_t>(found->capacity())) {return {EnrollStatus::waitlisted, 0};} -
In
MemoryStore::add_course:if (!domain::Course::is_valid_capacity(course.capacity())) return false; -
In
Console’s enroll command:if (words[1].empty() || words[1][0] != 'S') return "refused: student ids start with S";
Show the explained answer
- Presentation reaching infrastructure and the domain. The
console skips the application, so any rule the report gains, such as
hiding students who asked not to be listed, is skipped too. In the
example it would not even compile: the console cannot see
memory_store.hpporcourse.hpp. - The domain doing I/O. The rules now depend on a stream and a
message format. Tests of
Coursemust capturestd::cout, and changing email to SMS changes the domain. Return the outcome and let the application send the message. - A rule in the application layer. The capacity check is the
domain’s job, and here it is wrong as well: the student is reported
as waitlisted, but nothing added them to the waitlist. This is the
anemic-model mistake, even though
Coursestill has its ownenroll. The check also runs before the duplicate checks, so a seated student who enrolls again in a full course is told “waitlisted”, with position 0 and no notification. - No layer rule is broken. Infrastructure may use the domain,
and it asks the domain’s rule instead of deciding its own. It is
still dead code:
Course’s constructor already refuses such a capacity, so the condition is never true andreturn falseis never reached. Remove it. - A business rule in the presentation layer, if “ids start with S” is a rule of the registrar’s office: a web form would have to repeat it. If it is only a check on the console’s input format, it belongs here. The answer depends on who owns the rule; the page on API contracts and validation placement covers this question.
Summary
Section titled “Summary”- The four layers are presentation, application, domain, and infrastructure. A layer may use the layers below it, never above.
- In this version the domain depends on nothing, and infrastructure depends on the domain because it stores domain objects. The classic stack, with infrastructure at the bottom, makes the rules depend on storage.
- Strict layering uses only the layer directly below; relaxed uses any lower layer. Be strict where skipping a layer would skip a rule.
- One library per layer, with include directories visible only to the layers allowed to use them, lets the build refuse a wrong include. Forward declarations let the application hide the layers below it.
- Control goes down and results come up, changing type at each boundary; each layer has its own testing seam, and each failure is detected by the layer that has the knowledge.
- An anemic domain model keeps only data in the domain and lets rules scatter across use cases.
- The application still names concrete infrastructure classes. The hexagonal architecture page removes that coupling.