Clean architecture concepts
What you will learn on this page
Section titled “What you will learn on this page”- The dependency rule: source code depends only inward, from details towards policy, across four rings named entities, use cases, interface adapters, and frameworks and drivers.
- What clean architecture adds to the hexagonal version: one interactor class per use case, an input boundary for each, plain request and response models that cross the boundary, and a controller and presenter where the console was.
- How to sort a function into a ring by what it knows: syntax, wording, sequencing, deciding, or storing.
- The classic output boundary, where a use case pushes its result to a presenter, and when that is better than returning it.
- How CMake libraries enforce the rule, and how each ring is tested alone.
- When the ceremony pays for itself, and when the hexagonal version, or something smaller, is the better choice.
One rule, four rings
Section titled “One rule, four rings”Clean architecture is one of a family of designs, with hexagonal and onion architecture, that share one rule. The name and its drawing of four rings are commonly associated with Robert C. Martin, who presented them as a synthesis of earlier designs, ports and adapters among them. The drawing is memorable; the part that matters is the dependency rule, which in this site’s words is: code in an inner ring never refers to code in an outer ring, whether a class, a function, or a data format. Every dependency in the source points inward.
“Names” means the C++ sense: an inner file does not #include an outer
header, does not mention an outer type, and does not take or return
one. Calls still go outward at run time, through interfaces the inner
ring owns, exactly as the hexagonal core calls its driven ports.
Text description of the diagram
Four nested rings, outermost first. Frameworks and drivers holds main, std::cout, and the script. Inside it, interface adapters holds the ConsoleController with the present functions, and the gateway adapters MemoryCourses, MemoryStudents, and StreamNotifier. Inside that, use cases holds three groups: the request and response models with the input boundaries; the five interactors, such as EnrollStudent and DropStudent; and the gateways CourseGateway, StudentGateway, and Notifier. At the centre, entities holds entities::Course with the seat rules. Arrows, all pointing inward: main creates and wires the controller, the interactors, and the gateway adapters. The controller calls and depends on the input boundaries and models. The interactors implement the input boundaries, call the gateways, and use Course. The gateway adapters implement the gateways. The gateways name Course. Nothing in an inner ring points to anything in a ring outside it.
Diagram source (Mermaid)
flowchart LR
subgraph FD["frameworks and drivers"]
Main["main, std::cout<br/>the script"]
subgraph IA["interface adapters"]
Ctl["ConsoleController<br/>and present functions"]
Gw["MemoryCourses, MemoryStudents<br/>StreamNotifier"]
subgraph UC["use cases"]
Bnd["request and response models<br/>input boundaries"]
Int["EnrollStudent, DropStudent<br/>and three more interactors"]
Gt["CourseGateway, StudentGateway<br/>Notifier"]
subgraph EN["entities"]
Crs["entities::Course<br/>seat rules"]
end
end
end
end
Main -->|creates and wires| Ctl
Main -->|creates and wires| Int
Main -->|creates and wires| Gw
Ctl -->|calls, depends on| Bnd
Int ==>|implements| Bnd
Int -->|calls| Gt
Int -->|uses| Crs
Gw ==>|implements| Gt
Gt -->|names| Crs| Ring | Holds | Here | Changes when |
|---|---|---|---|
| Entities | The rules that would hold even without this program | entities::Course: seats, waitlist, promotion |
The university changes its rules |
| Use cases | What this program does, step by step, and what it needs | five interactors, their models and boundaries, three gateways | The registrar’s office changes a procedure |
| Interface adapters | Translation between use-case data and outside formats | controller, presenter, in-memory gateways, stream notifier | A command’s syntax, a reply’s wording, a storage format |
| Frameworks and drivers | The tools themselves, and the code that starts everything | main, std::cout, the console itself |
A tool is replaced |
The language and its standard library are not in any ring. They are
the platform every ring stands on, so the entity may use
std::vector and std::string freely. The rule is about this
program’s own code and about frameworks, libraries that would tie the
rules to one technology.
The number four is not part of the rule. A small program may merge two rings; a large one may split one. What must not change is the direction.
What clean architecture adds to hexagonal
Section titled “What clean architecture adds to hexagonal”The hexagonal version already obeys the dependency rule: its core is the inner two rings, and its adapters are the outer two. Clean architecture keeps that and adds four refinements, each with a cost.
| Hexagonal version | Clean version |
|---|---|
One EnrollmentService with five functions |
Five interactor classes, one per use case |
One driving port, EnrollmentUseCases |
Five input boundaries, one per use case |
| Functions take strings, return result structs | Each use case takes a request model and returns a response model |
One Console adapter |
A controller (syntax) and a presenter (wording) |
| Driven ports | The same interfaces, called gateways |
The terms are worth knowing because they are common in code reviews and job interviews. The refinements are worth using only when their problems are yours; the last sections of this page come back to that.
Step 1: sort the functions by what they know
Section titled “Step 1: sort the functions by what they know”The clean version is the hexagonal version’s code redistributed. To place each function, ask what it has to know:
| A function that knows… | Example | Goes in |
|---|---|---|
| Syntax: how a command is spelled | enroll <student> <course> has three words |
controller (interface adapters) |
| Wording: how a result is said | “ok: S1 waitlisted for CS101 (position 3)” | presenter (interface adapters) |
| Sequence: the steps of one use case | check student, find course, decide, save, notify | interactor (use cases) |
| Policy: what is allowed | a full course puts the student on the waitlist | entity |
| Storage or delivery: a technology | keep courses in a std::map; write a line |
gateway adapter (interface adapters) |
The hexagonal Console::run knew both syntax and wording. That was
fine there; here they split, so that each can be read, tested, and
changed alone. A second syntax, such as a one-command CLI, can reuse
the presenter’s sentences without the console’s parsing. The reverse
is not free in this example: the controller calls console::present
itself, so a different wording for the same commands needs either a
second controller or the output-boundary form described below, where
the presenter is passed in.
Then sort the data members:
- An interactor holds only pointers to the gateways it uses. It has no state of its own; calls share state only through the gateways, which is where the stored data lives.
- The controller holds references to the input boundaries it calls, and nothing else.
- The presenter here holds nothing at all, so it is a set of functions, not a class. Here, a class with no data members and no virtual functions would be a namespace with extra syntax.
- The gateway adapters hold the stored data; the entity holds the state the rules depend on.
Use-case interactors
Section titled “Use-case interactors”An interactor is one use case as one class. Its constructor is its list of needs:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// One use case, one class. Its constructor lists exactly what this use// case needs: it reads students, reads and writes courses, and notifies.// It is an "interactor": the class that carries out the enroll use case.// It implements EnrollStudentInput (the input boundary the controller// calls), and `final` says no class may derive from it in turn.// It owns nothing: the gateways and the notifier belong to whoever built// it (main, in this program), and it only borrows them.class EnrollStudent final : public EnrollStudentInput {public: // All three must outlive the interactor. // The parameters are references, so a caller cannot pass "nothing"; // the constructor stores their addresses (&students and so on) in // pointer members. `const StudentGateway&` means this use case can // only call the gateway's const functions, such as find: it can look // students up but never add one. EnrollStudent(const StudentGateway& students, CourseGateway& courses, Notifier& notifier) : students_{&students}, courses_{&courses}, notifier_{¬ifier} {}
// Runs the use case for one request (a student id and a course code) // and returns a response saying what happened. A refusal, such as an // unknown student, is a status in the response, not an exception. // `override` asks the compiler to check that this really replaces the // virtual execute declared in EnrollStudentInput. EnrollResponse execute(const EnrollRequest& request) override;
private: // Pointers rather than reference members, so the class can still be // assigned; the constructor sets them from references, so they are // never null. const StudentGateway* students_; // non-owning, never null; read only CourseGateway* courses_; // non-owning, never null Notifier* notifier_; // non-owning, never null};The constructors of the five interactors say what each one depends on, which the hexagonal service’s one constructor could not:
| Interactor | Students | Courses | Notifier |
|---|---|---|---|
AddCourse |
— | add only | — |
AddStudent |
add only | — | — |
EnrollStudent |
read only (const&) |
read and write | yes |
DropStudent |
— | read and write | yes |
ReportCourse |
read only (const&) |
read only (const&) |
— |
DropStudent has no student gateway because dropping never checks
registration, and ReportCourse holds both gateways as pointers to
const, so the compiler refuses any attempt to save from a report.
The hexagonal service gave every use case all three ports, so none of
this was visible or enforced.
The body is the hexagonal enroll, now reading a request and
building a response:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The enroll use case, start to finish: check the student exists, load a// copy of the course, let the course (the entity) apply its seat and// waitlist rules, and, if the course changed, store it and tell the// student. Every path returns an EnrollResponse; a refusal is a status,// not an exception. A gateway or the notifier could still throw (an// out-of-memory error, say); nothing here catches that.EnrollResponse EnrollStudent::execute(const EnrollRequest& request) { // A small local function (a lambda) that builds the response. Every // return below goes through it, so each response repeats the request's // student and course without any return having to remember to. // [&request] lets the lambda use `request` without copying it; that is // safe because the lambda is only called inside this function. // `position = 0` is a default argument: callers that have no waitlist // position just leave it out. const auto respond = [&request](EnrollStatus status, std::size_t position = 0) { return EnrollResponse{status, request.student, request.course, position}; }; // find returns a std::optional<Student>: empty if there is no such // student. `!` on an optional is true when it is empty, so an unknown // student is refused here, before the course is even looked up. if (!students_->find(request.student)) return respond(EnrollStatus::no_such_student); // The gateway hands back a copy of the stored course (or nothing). // Changing `found` does not change the stored course until save(). std::optional<entities::Course> found = courses_->find(request.course); // a copy if (!found) return respond(EnrollStatus::no_such_course);
// `found->` reaches the Course inside the optional (it is not empty // here). The entity applies the rules and says what it did. const entities::EnrollOutcome outcome = found->enroll(request.student); // the entity decides // One case per outcome. Only the first two changed the course, so only // they save it and send a message; the "already" cases change nothing. switch (outcome.kind) { case entities::EnrollOutcome::Kind::seated: // *found is the Course itself; save replaces the stored course with it. courses_->save(*found); // save first: nobody is told about a change that was lost // course_name (a helper in course_name.hpp) gives code and title, // such as "CS101 Software Design". notifier_->notify(request.student, "you have a seat in " + course_name(*found)); return respond(EnrollStatus::seated); case entities::EnrollOutcome::Kind::waitlisted: courses_->save(*found); // std::to_string turns the position number into text for the message. notifier_->notify(request.student, "you are number " + std::to_string(outcome.position) + " on the waitlist for " + course_name(*found)); return respond(EnrollStatus::waitlisted, outcome.position); case entities::EnrollOutcome::Kind::already_seated: return respond(EnrollStatus::already_seated); case entities::EnrollOutcome::Kind::already_waitlisted: return respond(EnrollStatus::already_waitlisted); } // Each case above returns, so this line only satisfies the compiler, // which cannot be sure an enum holds one of its named values. return respond(EnrollStatus::no_such_course); // not reached: every kind is handled above}How this code works: EnrollStudent::execute
execute has three parts: look up, decide, and record.
- Look up. The student gateway’s
findreturns an emptystd::optionalfor an unknown id, and the interactor answersno_such_studentat once. Only then is the course looked up; an unknown code givesno_such_course. Each refusal leaves throughrespond, so nothing has been changed or sent. - Decide.
courses_->findreturns a copy of the stored course.found->enroll(...)changes that copy and returns anEnrollOutcome. The rules (already seated? already waiting? a free seat?) live in the entity, not here. - Record. Only
seatedandwaitlistedchanged the copy, so only those two cases callsave, which replaces the stored course with the changed copy, and thennotify. The order is deliberate: ifsavethrew, nobody would have been told about a change that was not kept. The two “already” cases return without saving or notifying.
The interactor owns none of the objects it uses: the gateways and the
notifier are borrowed through pointers, and the course copy is a local
variable that is destroyed when execute returns.
A worked example from the program’s script. CS101 has 2 seats, and
S1 and S2 already hold them:
| Request | Student found? | Course found? | enroll outcome |
Saved and notified? | Response |
|---|---|---|---|---|---|
S3, CS101 |
yes | yes | waitlisted, 1 |
yes | waitlisted, position 1 |
S3, CS101 |
yes | yes | already_waitlisted |
no | already_waitlisted |
S9, CS101 |
no | not asked | not called | no | no_such_student |
The local lambda respond builds every response from the request, so
no return statement can forget to echo the student or the course. It
captures request by reference, which is safe because the lambda
never outlives the call.
Request and response models
Section titled “Request and response models”A request model is what one use case needs to start; a response model is everything an outer ring may learn from it. Both are plain structs of standard types:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// What the enroll use case needs to start: which student, which course.// Both are plain std::string ids ("S1", "CS101"), not entity types, so a// controller can build one without including any entity header.struct EnrollRequest { std::string student; std::string course;};
// Every way an enroll request can end. The first two mean the course// changed; the other four are refusals and change nothing. `enum class`// keeps the names inside the type, so code writes EnrollStatus::seated.enum class EnrollStatus { seated, waitlisted, already_seated, already_waitlisted, no_such_student, no_such_course,};
// Carries everything a presenter needs, including what was asked, so a// presenter never needs the request.// The `= ...` after each member is its default, used when a response is// made without that value. position is only meaningful for waitlisted;// it stays 0 for every other status.struct EnrollResponse { EnrollStatus status = EnrollStatus::no_such_course; std::string student; std::string course; std::size_t position = 0; // place on the waitlist, from 1, when waitlisted};Two choices in this file are deliberate:
- No entity crosses the boundary.
EnrollResponseholds strings and a number, not anentities::Course. If it held a course, the controller’s library would need the entities’ include directory, every change toCoursewould recompile the console, and console code would be tempted to make decisions from the course’s state that belong to the use case or the entity. - The response echoes the request. It carries
studentandcourseso that a presenter can word the reply from the response alone. A presenter that needed the request too would have to be handed both, and every caller would have to keep them together.
Models cost copying and mapping: the interactor copies strings out of the request and into the response. That is a few short strings per command here. In a system where each ring defines its own models for the same data and copies field by field between them, the mapping code can outgrow the rules; the DTO page covers when separate models are worth it.
Input boundaries
Section titled “Input boundaries”Each use case has an input boundary: an interface the controller calls and the interactor implements. All five live in the use-cases ring, next to the models:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The input boundary of the enroll use case: an interface with one job,// "run enroll for this request and give me the response". The console's// controller calls it; the EnrollStudent interactor implements it. The// controller therefore depends on this small header and the models, never// on the interactor, the gateways, or the entities.class EnrollStudentInput {public: // Virtual, so destroying an interactor through a pointer or reference // to this interface runs the right destructor. virtual ~EnrollStudentInput() = default; // `= 0` makes this a pure virtual function: the interface has no body // for it, and each implementation must supply one. virtual EnrollResponse execute(const EnrollRequest& request) = 0;
// Protected special members: only derived classes can construct, copy, // or assign the interface part. Outside code cannot assign one object // to another through EnrollStudentInput references, which would copy // only the interface part (slicing). The idiom reference's section on // interfaces explains this pattern.protected: EnrollStudentInput() = default; EnrollStudentInput(const EnrollStudentInput&) = default; EnrollStudentInput& operator=(const EnrollStudentInput&) = default;};The interface is what lets the console’s library link only the
boundary, never the interactors, and what lets the controller’s tests
use a fake. Reporting changes nothing, so ReportCourseInput::execute
is const.
The controller and the presenter
Section titled “The controller and the presenter”The controller holds the input boundaries it may call. They are references because none may be missing:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The input boundaries the console can call. References, because none// may be missing; every one must outlive the controller.// Each member names an interface, not an interactor class, so the console// never sees how a use case is carried out. `report` is a const reference// because ReportCourseInput::execute is const: reporting changes nothing.struct UseCaseInputs { use_cases::AddCourseInput& add_course; use_cases::AddStudentInput& add_student; use_cases::EnrollStudentInput& enroll; use_cases::DropStudentInput& drop; const use_cases::ReportCourseInput& report;};
// The console's controller: turns a command line into a request model,// calls one input boundary, and hands the response to the presenter.// It refuses only bad syntax; it never applies a rule such as "no free// seat" (the use case's job) and never words a result (the presenter's).class ConsoleController {public: // `explicit` stops a UseCaseInputs from turning into a controller // by accident. Copying the struct copies the five references, not the // objects they refer to. explicit ConsoleController(const UseCaseInputs& inputs) : inputs_{inputs} {}
// Runs one command line and returns the reply, "ok: ..." or "refused: ...". // std::string_view is a read-only view of text the caller owns; run // does not keep it after it returns. std::string run(std::string_view line);
private: UseCaseInputs inputs_; // a copy of the references: non-owning};Storing a struct of references makes ConsoleController impossible
to copy-assign, which is harmless here: the program creates one
controller and never reassigns it. The references are non-owning;
main owns everything they refer to and outlives the controller.
run knows only syntax. It turns words into a request model, calls
one boundary, and passes the response to the presenter:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// One command line in, one reply out. The steps for every command are the// same: split the line into words, check the word count (and, for course,// that the capacity is a number), build the request model, call one input// boundary, and pass its response to the matching present overload.// Bad syntax is refused here, before any use case is called.std::string ConsoleController::run(std::string_view line) { // split (a helper earlier in this file) breaks the line at spaces: // "enroll S1 CS101" becomes {"enroll", "S1", "CS101"}. const Words words = split(line); if (words.empty()) return refuse_empty(); // A reference to the first word, so it is not copied. const std::string& command = words[0];
if (command == "course") { // course needs a code, a capacity, and at least one word of title. if (words.size() < 4) return refuse_usage("course <code> <capacity> <title>"); // whole_number (a helper in this file) gives an empty optional for // text that is not entirely a number, such as "2x". const std::optional<int> capacity = whole_number(words[2]); if (!capacity) return refuse_bad_capacity(); // the controller knows the syntax // The braces build an AddCourseRequest {code, capacity, title}. // *capacity takes the int out of the optional; join_from(words, 3) // glues the title words back together: "Software Design". // execute returns an AddCourseResponse, so the present overload for // that type is the one called. return present(inputs_.add_course.execute({words[1], *capacity, join_from(words, 3)})); } if (command == "student") { // The name may be several words: everything after the id. if (words.size() < 3) return refuse_usage("student <id> <name>"); return present(inputs_.add_student.execute({words[1], join_from(words, 2)})); } if (command == "enroll") { // Exactly three words: the command, a student id, a course code. // {words[1], words[2]} builds the EnrollRequest {student, course}. if (words.size() != 3) return refuse_usage("enroll <student> <course>"); return present(inputs_.enroll.execute({words[1], words[2]})); } if (command == "drop") { if (words.size() != 3) return refuse_usage("drop <student> <course>"); return present(inputs_.drop.execute({words[1], words[2]})); } if (command == "report") { if (words.size() != 2) return refuse_usage("report <course>"); return present(inputs_.report.execute({words[1]})); } // No branch matched the first word. return refuse_unknown(command);}The presenter knows only wording. Each present overload takes one
response model and returns the reply text, which is the console’s
entire view model: the data a view shows, already in display
form.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The console's presenter: turns each response model into the reply// text, which is the console's whole view model. It keeps no state, so// it is a set of functions rather than a class.// All five share the name `present`; they are overloads, and the compiler// picks the one whose parameter type matches the response passed in. That// is why the controller can write present(...execute(...)) for every// command without naming a different function each time.std::string present(const use_cases::AddCourseResponse& response);std::string present(const use_cases::AddStudentResponse& response);std::string present(const use_cases::EnrollResponse& response);std::string present(const use_cases::DropResponse& response);std::string present(const use_cases::ReportResponse& response);
// Replies for input the controller could not turn into a request.// They live here, with the other wording, so the presenter writes every// reply; only the usage text, such as "report <course>", comes from the// controller. The controller calls them; no use case is involved.std::string refuse_empty();std::string refuse_unknown(std::string_view command);std::string refuse_usage(std::string_view usage);std::string refuse_bad_capacity();VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Words one enroll response as the console's reply: "ok: ..." for the two// statuses that changed the course, "refused: ..." for the four that did// not. It makes no decisions; the status already says what happened, and// the response carries the ids to name.std::string present(const use_cases::EnrollResponse& response) { // Short names for the two ids. They are references, so nothing is copied. const std::string& student = response.student; const std::string& code = response.course; // Lets the cases below say EnrollStatus::seated instead of // use_cases::EnrollStatus::seated. using use_cases::EnrollStatus; // One case per status, each returning its text at once. switch (response.status) { case EnrollStatus::seated: return "ok: " + student + " enrolled in " + code; case EnrollStatus::waitlisted: // Only here is position used: 1 means first in line. return "ok: " + student + " waitlisted for " + code + " (position " + std::to_string(response.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; } // Every status returns above; this line only satisfies the compiler. return "refused: no course " + code; // not reached}How this code works: One enroll command, ring by ring
Follow the line enroll S3 CS101 from the script, at the point where
S1 and S2 already hold both seats of CS101.
main(frameworks and drivers) prints> enroll S3 CS101and callscontroller.run(line).mainowns every object involved: the gateway adapters, the notifier, the five interactors, and the controller are its local variables.ConsoleController::run(interface adapters) splits the line into three words, checks there are exactly three, and builds the request modelEnrollRequest{"S3", "CS101"}. It callsinputs_.enroll.execute(...)through theEnrollStudentInputreference. This is the boundary: the controller knows only the interface and the models, and the call lands inEnrollStudentwithout the controller knowing that class exists.EnrollStudent::execute(use cases) findsS3through the student gateway and a copy ofCS101through the course gateway. Both gateways are interfaces from its own ring; the objects behind them areMemoryStudentsandMemoryCoursesfrom the outer ring.Course::enroll(entities) findsS3in neither list and no free seat, so it appendsS3to the copy’s waitlist and returnswaitlistedwith position 1.- Back in the interactor,
savestores the changed copy, andnotifymakes theStreamNotifierprintnotify S3: you are number 1 on the waitlist for CS101 Software Design. The interactor returnsEnrollResponse{waitlisted, "S3", "CS101", 1}, plain data with no entity in it. present(interface adapters) is chosen by overloading, because the argument is anEnrollResponse. It returnsok: S3 waitlisted for CS101 (position 1).mainprints that reply. The notification line appeared first, because it was printed during step 5, whilerunwas still working.
Each arrow points inward or stays in one ring: the controller calls an interface owned by the use cases, the interactor calls gateway interfaces defined in its own ring and an entity, and nothing inner names the console. The response’s journey outward is a return value, not a call.
A malformed capacity such as 2x gets the same reply as a capacity of
0, but by a different path: the controller refuses 2x because it is
not a number, which only the controller can know, and AddCourse
refuses 0 because the entity says a course needs a seat.
class console::ConsoleController
interface adapters
Data members
UseCaseInputs inputs_;references to five input boundaries, non-owning
Member functions
std::string run(std::string_view line);
class use_cases::EnrollStudentInput
use cases: input boundary, abstract
Member functions
virtual EnrollResponse execute(const EnrollRequest& request) = 0;
class use_cases::EnrollStudent
use cases: interactor, final, implements EnrollStudentInput
Data members
const StudentGateway* students_;non-owning, never null; read onlyCourseGateway* courses_;non-owning, never nullNotifier* notifier_;non-owning, never null
Member functions
EnrollResponse execute(const EnrollRequest& request) override;
class use_cases::CourseGateway
use cases: gateway, abstract
Member functions
virtual std::optional<entities::Course> find(const entities::CourseCode& code) const = 0;virtual void save(const entities::Course& course) = 0;
class adapters::MemoryCourses
interface adapters, implements CourseGateway
Data members
std::map<entities::CourseCode, entities::Course> courses_;
class entities::Course
entities
Data members
std::vector<StudentId> seated_;size() <= capacity_std::deque<StudentId> waitlist_;first in line first
Member functions
EnrollOutcome enroll(const StudentId& student);
Text description of the diagram
A sequence diagram for one enroll command. The ConsoleController calls EnrollStudent’s execute with a request for S3 and CS101. The interactor asks the gateways to find S3 and CS101 and gets a student and a copy of the course. It asks the copy to enroll S3, and the course answers waitlisted, position 1. The interactor saves the copy, then notifies S3, both through gateways. It returns a response holding waitlisted, S3, CS101, and position 1 to the controller. The controller passes the response to the present function, which returns the reply text “ok: S3 waitlisted for CS101 (position 1)”.
Diagram source (Mermaid)
sequenceDiagram
participant C as ConsoleController
participant I as EnrollStudent
participant G as gateways
participant E as Course copy
participant P as present
C->>I: execute, request S3 and CS101
I->>G: find S3, find CS101
G-->>I: a student, a copy of the course
I->>E: enroll S3
E-->>I: waitlisted, position 1
I->>G: save the copy, then notify S3
I-->>C: response waitlisted, S3, CS101, 1
C->>P: present the response
P-->>C: ok, S3 waitlisted for CS101, position 1The classic flow: an output boundary
Section titled “The classic flow: an output boundary”In the classic description, the interactor does not return its response. It hands it to an output boundary, an interface the use-cases ring owns and a presenter object implements; the presenter stores a view model for the view to read. The example keeps a compiled version of that flow for the enroll use case, used only by a test:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The output boundary: an interface the use case calls to hand over its// result. A presenter implements it. present returns void, so the result// travels by this call ("push") instead of as a return value.class EnrollStudentOutput {public: virtual ~EnrollStudentOutput() = default; // `= 0`: every presenter must say what it does with a response. virtual void present(const use_cases::EnrollResponse& response) = 0;
protected: EnrollStudentOutput() = default; EnrollStudentOutput(const EnrollStudentOutput&) = default; EnrollStudentOutput& operator=(const EnrollStudentOutput&) = default;};
// The push form of the enroll use case. It reuses the returning// interactor, so the rules are written once.class PresentingEnrollStudent {public: // Both must outlive this object. PresentingEnrollStudent(use_cases::EnrollStudentInput& use_case, EnrollStudentOutput& output) : use_case_{&use_case}, output_{&output} {}
// Returns nothing: the response goes to the output boundary instead. // Read it inside out: use_case_->execute(request) runs the real enroll // interactor and returns its EnrollResponse, and that response is // passed straight to output_->present. So exactly one present call // happens per execute, unless execute throws. void execute(const use_cases::EnrollRequest& request) { output_->present(use_case_->execute(request)); }
private: use_cases::EnrollStudentInput* use_case_; // non-owning, never null EnrollStudentOutput* output_; // non-owning, never null};
// A presenter object: it keeps the view model until the view reads it.class ConsoleEnrollPresenter final : public EnrollStudentOutput {public: // Words the response with the console's existing console::present // and stores the text in view_model_, replacing the previous one. void present(const use_cases::EnrollResponse& response) override; // A reference to the stored text. Read it before the next present // call: that call overwrites the string. const std::string& view_model() const { return view_model_; }
private: std::string view_model_; // the last reply; empty until the first present};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The push form gives the same text as the returning form; the// presenter object holds it until a view reads it.// LLD_TEST(name) defines one test, and LLD_CHECK_EQ(actual, expected)// records a failure if the two values are not equal. Both come from the// site's small test header, lld_test.hpp.// namespace { ... } with no name keeps the helper private to this file.namespace {
// A notifier that ignores every message: this test is about the reply// text, not about notifications. The parameters have no names because// the body does not use them.struct SilentNotifier final : use_cases::Notifier { void notify(const entities::StudentId&, std::string_view) override {}};
} // namespace
// Sets up one course with one seat and one student, wires the real enroll// interactor into the push form, and enrolls the same student twice.// Proves the presenter object receives each response and holds its text:// first the seated reply, then (after the second call overwrites it) the// "already enrolled" refusal.LLD_TEST(the_presenter_object_receives_the_response) { adapters::MemoryCourses courses; adapters::MemoryStudents students; SilentNotifier notifier; // add returns a bool (false if the code or id is taken); these tests // start from empty stores, so the result is not checked. courses.add(entities::Course{"CS101", "Software Design", 1}); students.add(entities::Student{"S1", "Ada Lovelace"}); use_cases::EnrollStudent enroll{students, courses, notifier};
variants::ConsoleEnrollPresenter presenter; // pushing borrows enroll and presenter; both live until the test ends. variants::PresentingEnrollStudent pushing{enroll, presenter}; // {"S1", "CS101"} builds the EnrollRequest {student, course}. pushing.execute({"S1", "CS101"}); LLD_CHECK_EQ(presenter.view_model(), std::string{"ok: S1 enrolled in CS101"}); pushing.execute({"S1", "CS101"}); LLD_CHECK_EQ(presenter.view_model(), std::string{"refused: S1 is already enrolled in CS101"});}Both forms obey the dependency rule: EnrollStudentOutput would live
in the use-cases ring, and the presenter in the adapters ring
implements it. The difference is control flow, not dependency
direction. PresentingEnrollStudent is built on top of the returning
interactor to show that, for a synchronous call that produces exactly
one result, the two are equivalent.
Returning the response is the better default in C++: the result type
is in the signature, the compiler warns about a path that returns
nothing (with push, nothing checks that present was called at
all), and nothing has to hold a view model between calls. The push
form earns its interface when:
- a use case produces zero, one, or several outputs, such as progress updates during a long import;
- the result arrives later, on another thread or after a network reply, so there is nothing to return yet;
- the presenter must be chosen per call by the use case, for example a different output for a refused request.
The presenter object also brings a lifetime question that returning
avoids: the view must read view_model() after execute and before
the next call overwrites it.
Making the build enforce the rule
Section titled “Making the build enforce the rule”Each ring, or each part of one, is its own library:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
# One library per ring, or per part of a ring, so that each part can# include only what the dependency rule allows.
# Entities: the innermost ring. It links nothing.add_library(arch_clean_entities STATIC entities/course.cpp)target_include_directories(arch_clean_entities PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/entities)
# Use cases. The boundary (request and response models, input# boundaries) names no entity; the gateways do; the interactors use both.add_library(arch_clean_boundary INTERFACE)target_include_directories(arch_clean_boundary INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/use_cases/boundary)
add_library(arch_clean_gateways INTERFACE)target_include_directories(arch_clean_gateways INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/use_cases/gateways)target_link_libraries(arch_clean_gateways INTERFACE arch_clean_entities)
add_library(arch_clean_interactors STATIC use_cases/interactors/add_course.cpp use_cases/interactors/add_student.cpp use_cases/interactors/enroll_student.cpp use_cases/interactors/drop_student.cpp use_cases/interactors/report_course.cpp)target_include_directories(arch_clean_interactors PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/use_cases/interactors)target_link_libraries(arch_clean_interactors PUBLIC arch_clean_boundary arch_clean_gateways)
# Interface adapters. The console sees only the boundary; the gateway# adapters see only the gateways.add_library(arch_clean_console STATIC interface_adapters/console/console_controller.cpp interface_adapters/console/console_presenter.cpp)target_include_directories(arch_clean_console PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/interface_adapters/console)target_link_libraries(arch_clean_console PUBLIC arch_clean_boundary)
add_library(arch_clean_gateway_adapters STATIC interface_adapters/memory/memory_gateways.cpp interface_adapters/stream/stream_notifier.cpp)target_include_directories(arch_clean_gateway_adapters PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/interface_adapters/memory ${CMAKE_CURRENT_SOURCE_DIR}/interface_adapters/stream)target_link_libraries(arch_clean_gateway_adapters PUBLIC arch_clean_gateways)
# Frameworks and drivers: main, the outermost ring, links everything.lld_add_example(arch_enrollment_clean SOURCES main.cpp EXPECTED_OUTPUT expected_output.txt)target_link_libraries(arch_enrollment_clean PRIVATE arch_clean_console arch_clean_interactors arch_clean_gateway_adapters)
lld_add_test(arch_clean_interactor_tests SOURCES tests/test_interactors.cpp)target_link_libraries(arch_clean_interactor_tests PRIVATE arch_clean_interactors arch_clean_gateway_adapters)
lld_add_test(arch_clean_presenter_tests SOURCES tests/test_presenter.cpp)target_link_libraries(arch_clean_presenter_tests PRIVATE arch_clean_console)
lld_add_test(arch_clean_controller_tests SOURCES tests/test_controller.cpp)target_link_libraries(arch_clean_controller_tests PRIVATE arch_clean_console)
# The push-style variant: only its test builds it.lld_add_test(arch_clean_output_boundary_tests SOURCES tests/test_output_boundary.cpp variants/presenting_enroll.cpp)target_include_directories(arch_clean_output_boundary_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/variants)target_link_libraries(arch_clean_output_boundary_tests PRIVATE arch_clean_console arch_clean_interactors arch_clean_gateway_adapters)
# The dependency rule, checked: console code that includes an entity# header, built with exactly what the console library provides, must# fail to compile. If the console library ever links the entities, the# file compiles and this test fails.add_executable(arch_clean_console_violation EXCLUDE_FROM_ALL checks/presenter_uses_entities.cpp)target_link_libraries(arch_clean_console_violation PRIVATE arch_clean_console)add_test(NAME arch_clean_console_cannot_see_entities COMMAND ${CMAKE_COMMAND} --build ${CMAKE_BINARY_DIR} --target arch_clean_console_violation)set_tests_properties(arch_clean_console_cannot_see_entities PROPERTIES PASS_REGULAR_EXPRESSION "course.hpp.*(No such file or directory|file not found)" LABELS "test")| Library | Ring | Can include |
|---|---|---|
arch_clean_entities |
entities | itself only |
arch_clean_boundary |
use cases | itself only (no entity types) |
arch_clean_gateways |
use cases | entities |
arch_clean_interactors |
use cases | entities, boundary, gateways |
arch_clean_console |
interface adapters | boundary only |
arch_clean_gateway_adapters |
interface adapters | entities, gateways |
arch_enrollment_clean |
frameworks and drivers | everything |
The boundary library is what keeps the console out of the entities:
the models and input boundaries name no entity type, so the console
does not need the entities’ include directory and does not get it.
The test arch_clean_console_cannot_see_entities builds a file that
includes course.hpp, linked with the console library and nothing
else, and passes only if the compiler reports the header missing. If
someone later links the entities into the console library, the file
compiles and the test fails. As on the
hexagonal page, this controls include paths, not every possible
#include spelling, and it cannot stop a presenter from making a
policy decision. Review still matters.
The outermost ring
Section titled “The outermost ring”main is the frameworks-and-drivers ring and the composition root.
It creates the gateway adapters, then one interactor per use case with
only the gateways it needs, then the controller:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The outermost ring: main, std::cout, and the script. It is the only// code that knows every ring, and it wires them together.int main() { // The same script as version 0; the output must be the same text. // A fixed array of read-only text views. The quoted strings live for // the whole program, so the views never dangle; constexpr means the // array is built at compile time. 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", };
// The outer-ring adapters, created first because everything below // borrows them. main owns them as ordinary local variables: no new, no // smart pointers. The notifier writes each message to std::cout. adapters::MemoryCourses courses; adapters::MemoryStudents students; adapters::StreamNotifier notifier{std::cout};
// One object per use case, each given only the gateways it needs. // Each constructor takes references and keeps pointers, so these // objects borrow the adapters above and must not outlive them. use_cases::AddCourse add_course{courses}; use_cases::AddStudent add_student{students}; use_cases::EnrollStudent enroll{students, courses, notifier}; use_cases::DropStudent drop{courses, notifier}; use_cases::ReportCourse report{courses, students};
// The inner braces build a UseCaseInputs struct of five references, // in the struct's member order. Each interactor is passed as the input // boundary it implements, so the controller sees only the interfaces. console::ConsoleController controller{{add_course, add_student, enroll, drop, report}};
// Echo each command, run it, and print the reply. A string_view is // cheap to copy, so the loop takes each line by value. for (const std::string_view line : script) { std::cout << "> " << line << '\n'; const std::string reply = controller.run(line); // may print notifications first std::cout << reply << '\n'; }} // destroyed in reverse order of creation, borrowers firstThe wiring is now longer than the hexagonal version’s, and it grows by one line per use case. That is the price of the per-use-case constructors, and a reason larger programs give the composition root its own structure; the composition roots page covers that.
Same behaviour, different structure
Section titled “Same behaviour, different structure”> 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 text is identical to version 0’s, which a test checks.
Testing each ring alone
Section titled “Testing each ring alone”Interactors, each with only the gateways its constructor asks for.
The AddStudent test builds one in-memory gateway and nothing else.
The in-memory gateways are production adapters from the outer ring,
used here because they are fast and need no setup; a hand-written
fake would isolate the ring completely, at the cost of more test
code:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Each interactor is tested alone, built with only the gateways its// constructor asks for.// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure// if the condition is false, and LLD_CHECK_EQ(actual, expected) records one// if the two values differ. They come from the site's test header,// lld_test.hpp.// namespace { ... } with no name keeps the helper private to this file.namespace {
// A fake notifier that remembers every message instead of sending it, so// a test can check who was told what.struct RecordingNotifier final : use_cases::Notifier { std::vector<std::pair<std::string, std::string>> sent; // (to, text) // emplace_back builds the (to, text) pair in place at the end of the // vector. std::string{text} copies the text, because a string_view // only borrows text that may be gone after notify returns. void notify(const entities::StudentId& to, std::string_view text) override { sent.emplace_back(to, std::string{text}); }};
} // namespace
// Builds AddStudent with nothing but a student gateway: that is all it// asks for. Proves the first add of S1 succeeds and a second add with the// same id is refused, even with a different name.LLD_TEST(adding_a_student_needs_only_the_student_gateway) { adapters::MemoryStudents students; use_cases::AddStudent add_student{students}; LLD_CHECK(add_student.execute({"S1", "Ada Lovelace"}).status == use_cases::AddStudentStatus::added); LLD_CHECK(add_student.execute({"S1", "Someone Else"}).status == use_cases::AddStudentStatus::already_exists);}
// One course with one seat, one student. Proves enroll returns seated// with the request's ids echoed, that the change reached the store (a// fresh find shows S1 seated), and that exactly one message was sent.LLD_TEST(enrolling_saves_the_course_tells_the_student_and_echoes_the_request) { adapters::MemoryCourses courses; adapters::MemoryStudents students; RecordingNotifier notifier; courses.add(entities::Course{"CS101", "Software Design", 1}); students.add(entities::Student{"S1", "Ada Lovelace"});
use_cases::EnrollStudent enroll{students, courses, notifier}; const use_cases::EnrollResponse response = enroll.execute({"S1", "CS101"}); LLD_CHECK(response.status == use_cases::EnrollStatus::seated); LLD_CHECK_EQ(response.student, std::string{"S1"}); LLD_CHECK_EQ(response.course, std::string{"CS101"});
// A new copy from the store. `stored &&` checks it is not empty before // `->` reads it; && stops at the first false, so an empty optional is // never read. const std::optional<entities::Course> stored = courses.find("CS101"); LLD_CHECK(stored && stored->seated() == std::vector<std::string>{"S1"}); LLD_CHECK_EQ(notifier.sent.size(), std::size_t{1});}
// One seat: S1 takes it and S2 is waitlisted. Proves that when S1 drops,// S2 is promoted, the response names S2, and the last message went to S2.LLD_TEST(dropping_a_seat_promotes_and_tells_the_first_waiting_student) { adapters::MemoryCourses courses; adapters::MemoryStudents students; RecordingNotifier notifier; courses.add(entities::Course{"CS101", "Software Design", 1}); students.add(entities::Student{"S1", "Ada Lovelace"}); students.add(entities::Student{"S2", "Grace Hopper"}); use_cases::EnrollStudent enroll{students, courses, notifier}; // Setup only: the responses are not needed, so they are not stored. enroll.execute({"S1", "CS101"}); enroll.execute({"S2", "CS101"});
use_cases::DropStudent drop{courses, notifier}; // no student gateway needed const use_cases::DropResponse response = drop.execute({"S1", "CS101"}); LLD_CHECK(response.status == use_cases::DropStatus::left_seat); // Comparing with an optional holding "S2" is true only if promoted is // not empty and holds "S2". LLD_CHECK(response.promoted == std::optional<std::string>{"S2"}); // back() is the last message sent; .first is who it went to. LLD_CHECK_EQ(notifier.sent.back().first, std::string{"S2"});}
// Proves ReportCourse can be built from const references only (so it can// never write), finds an existing empty course with the right capacity,// and reports nothing for an unknown code.LLD_TEST(a_report_reads_through_const_gateways) { adapters::MemoryCourses courses; adapters::MemoryStudents students; courses.add(entities::Course{"CS101", "Software Design", 2}); // Read-only names for the same two stores: through these, only const // functions such as find can be called. const adapters::MemoryCourses& read_courses = courses; const adapters::MemoryStudents& read_students = students;
const use_cases::ReportCourse report{read_courses, read_students}; const use_cases::ReportResponse found = report.execute({"CS101"}); LLD_CHECK(found.report.has_value()); LLD_CHECK(found.report && found.report->capacity == 2 && found.report->seated.empty()); LLD_CHECK(!report.execute({"CS999"}).report.has_value());}The presenter, with hand-made response models. No use case, gateway, or entity is linked into this test program:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The presenter is tested with hand-made response models. No use case,// gateway, or entity exists in this test program.// LLD_TEST(name) defines one test; LLD_CHECK_EQ(actual, expected) records// a failure if the two differ. Both come from lld_test.hpp.
// Two responses built by hand, in member order {status, student, course,// position}. Proves the waitlisted reply shows the position and the// unknown-student reply names the student.LLD_TEST(the_presenter_words_each_enroll_response) { using use_cases::EnrollStatus; const use_cases::EnrollResponse waitlisted{EnrollStatus::waitlisted, "S1", "CS101", 3}; LLD_CHECK_EQ(console::present(waitlisted), std::string{"ok: S1 waitlisted for CS101 (position 3)"}); const use_cases::EnrollResponse unknown{EnrollStatus::no_such_student, "S9", "CS101", 0}; LLD_CHECK_EQ(console::present(unknown), std::string{"refused: no student S9"});}
// A report for a two-seat course with one seated student and an empty// waitlist. Proves the three-line layout: the seat count "1/2", the seated// names, and "(none)" for an empty list. The nested braces fill// ReportResponse {course, report}, CourseReport {title, capacity, seated,// waitlist}, and one StudentLine {id, name}; the final {} is the empty// waitlist. The adjacent string literals below join into one string.LLD_TEST(the_presenter_lays_out_a_report) { const use_cases::ReportResponse response{ "CS101", use_cases::CourseReport{"Software Design", 2, {{"S2", "Grace Hopper"}}, {}}}; LLD_CHECK_EQ(console::present(response), std::string{"ok: CS101 Software Design, 1/2 seats taken\n" " seated: S2 Grace Hopper\n" " waitlist: (none)"});}The controller, with one fake that implements all five input
boundaries. Each execute overrides the matching base class’s
function, because each takes a different request type:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The controller is tested with one fake that implements all five input// boundaries and records what it was asked.// LLD_TEST(name) defines one test; LLD_CHECK_EQ(actual, expected) records// a failure if the two differ. Both come from lld_test.hpp.namespace {
// One class that derives from all five input boundaries at once, so the// same object can be passed for every member of UseCaseInputs. Each// execute takes a different request type, so each one overrides the// matching base's function. It runs no rules: it counts calls, remembers// the last course and enroll requests, and returns a fixed answer.struct FakeUseCases final : use_cases::AddCourseInput, use_cases::AddStudentInput, use_cases::EnrollStudentInput, use_cases::DropStudentInput, use_cases::ReportCourseInput { use_cases::AddCourseRequest last_course; use_cases::EnrollRequest last_enroll; int calls = 0;
use_cases::AddCourseResponse execute(const use_cases::AddCourseRequest& request) override { ++calls; last_course = request; return {use_cases::AddCourseStatus::added, request.code}; } use_cases::AddStudentResponse execute(const use_cases::AddStudentRequest& request) override { ++calls; return {use_cases::AddStudentStatus::added, request.id}; } use_cases::EnrollResponse execute(const use_cases::EnrollRequest& request) override { ++calls; last_enroll = request; return {use_cases::EnrollStatus::seated, request.student, request.course, 0}; } use_cases::DropResponse execute(const use_cases::DropRequest& request) override { ++calls; return {use_cases::DropStatus::not_in_course, request.student, request.course, std::nullopt}; } // This one is const (as ReportCourseInput requires), so it cannot // change `calls`; no test here sends a report command. use_cases::ReportResponse execute(const use_cases::ReportRequest& request) const override { return {request.course, std::nullopt}; }};
} // namespace
// Proves the controller splits the words into the right request fields:// the capacity text "30" becomes the int 30, the title words are joined// back into "Software Design", and enroll's two ids land in student and// course. The reply comes from the real presenter.LLD_TEST(the_controller_builds_requests_from_the_words) { FakeUseCases fake; // The same fake fills all five slots, each as a different interface. console::ConsoleController controller{{fake, fake, fake, fake, fake}}; LLD_CHECK_EQ(controller.run("course CS101 30 Software Design"), std::string{"ok: course CS101 added"}); LLD_CHECK_EQ(fake.last_course.capacity, 30); LLD_CHECK_EQ(fake.last_course.title, std::string{"Software Design"}); // The reply is not checked here, only the request the fake received. controller.run("enroll S1 CS101"); LLD_CHECK_EQ(fake.last_enroll.student, std::string{"S1"}); LLD_CHECK_EQ(fake.last_enroll.course, std::string{"CS101"});}
// A capacity that is not a number, a missing word, and an unknown command.// Proves each gets its refusal text and that calls is still 0 at the end:// bad syntax never reaches a use case.LLD_TEST(the_controller_refuses_bad_input_without_calling_a_use_case) { FakeUseCases fake; console::ConsoleController controller{{fake, fake, fake, fake, fake}}; LLD_CHECK_EQ(controller.run("course CS101 2x Software Design"), std::string{"refused: capacity must be a whole number of at least 1"}); LLD_CHECK_EQ(controller.run("enroll S1"), std::string{"refused: usage: enroll <student> <course>"}); LLD_CHECK_EQ(controller.run("teleport S1"), std::string{"refused: unknown command teleport"}); LLD_CHECK_EQ(fake.calls, 0);}The hexagonal console test checked parsing and wording together. Here each is checked where it lives, and a wording change touches only the presenter’s tests.
When the ceremony is worth it
Section titled “When the ceremony is worth it”The three versions of the same program, counting the .hpp and
.cpp files of the program itself (not tests, checks, the CLI, or the
output-boundary variant):
| Version | Files | Lines | Interfaces |
|---|---|---|---|
| Layered | 11 | 448 | 0 |
| Hexagonal | 17 | 525 | 4 |
| Clean | 25 | 700 | 8 |
The lines leave out blank lines and lines that hold only a comment (the files also carry explanatory comments for this site), so they count code; even so, they are a rough measure. The behaviour is identical in all three.
For this program, the clean version is more structure than the requirements ask for. Five use cases and one user interface do not need five input boundaries or a controller–presenter split; the hexagonal version gets the testability and the replaceable storage with half the interfaces. The clean version is shown at this size so that every part fits on one page.
The ceremony pays for itself when:
- there are many use cases, and different people own different ones, so one class per use case keeps changes and reviews apart;
- there are several delivery mechanisms (a web API, a console, a batch job) that share use cases but not syntax or wording;
- use cases need different dependencies, and making each constructor state them catches mistakes, such as a report that writes;
- the program will live for years, through several replacements of its frameworks.
It does not when:
- the program is create, read, update, delete over a few tables: the interactors would only pass data through, and the models would copy the records field by field;
- one small team owns everything and there is one user interface;
- the rings are adopted as folders without the build enforcing the direction: the cost is paid, and the benefit is not.
The cost of abstraction page gives the general test: an interface without variation, and without a test that needs a substitute, is indirection that only costs.
Common mistakes
Section titled “Common mistakes”- Entities as database records. An entity whose members mirror a table, with no rules, is the anemic model from the layered page in a new ring. Entities hold policy.
- Framework types in models. A response model holding a JSON object or a database row makes the use-cases ring depend on that library. Models use standard types.
- One model per ring for the same data. Copying
EnrollRequestinto anEnrollCommandinto anEnrollInput, field by field, adds mapping code and no protection. Add a model where two sides really need different shapes. - Interactors that call interactors. Shared steps go into the entity or a plain function.
- Presenters that decide. “Show the waitlist only if the course is full” is a rule if the registrar asked for it; the use case should say so in the response, and the presenter should only word it.
- “Clean” as a rule that every class needs an interface. The entity has none, and the presenter is not even a class. Interfaces go where the dependency rule needs to cross a ring boundary.
- Folders without enforcement. Ring-named directories that every target can include from are a diagram, not an architecture.
When the requirements change
Section titled “When the requirements change”- A JSON web API is added. Write a second controller that builds the same request models from HTTP requests, and a second presenter that turns responses into JSON. The interactors, models, and entities do not change. This is the change the use-case boundary was for.
- Reports become slow and move to a read-only replica.
ReportCoursealready takesconstgateways; give it a gateway adapter for the replica inmain. The other interactors keep the primary store. A replica adapter would still have to implementaddandsave, which it cannot honour; if this happens, split a reader interface out of each gateway, as the interface segregation principle suggests. - Enrollment must check prerequisites. The rule is policy and
goes into the entity, or a new entity for a student’s record. The
EnrollStudentinteractor gains one gateway to read passed courses; its constructor shows the new dependency, and only its tests and the one line inmainchange. - Progress is reported during a bulk import of a thousand students. This is the case where an output boundary pays: the import interactor reports progress several times per call.
Exercise
Section titled “Exercise”Exercise: Judge the fit for three applications
For each application, decide whether to use clean architecture as shown on this page, the hexagonal version, layers, or a single module. Justify the choice from the requirements, and name one part of clean architecture you would keep or drop.
- Grade converter. A script a teacher runs once a term: it reads a CSV file of marks, converts them to letter grades with a fixed table, and writes a report. One person maintains it.
- Clinic appointments. Patients book through a web site, a phone menu, and the front desk’s application; a nightly batch sends reminders. Booking rules (who may book which doctor, cancellation limits) change when regulations change, and three teams work on the system for years.
- Meeting-room admin tool. Office managers add, rename, and delete rooms and see a list of them, through one internal web form. There are no rules beyond “a name is required”.
Show the explained answer
- A single module, perhaps with a separate function for the conversion table so it can be tested. There is one use case, one input format, one output, one maintainer, and the table is the only rule. Rings, boundaries, and models would be several times the size of the program. Keep the one idea that is free: the conversion function takes values and returns values, with no file access, so a test can check it.
- Clean architecture, largely as shown. Several delivery mechanisms share the same use cases but not syntax or wording, which is what controllers and presenters are for. The rules change on their own schedule, so entities and interactors should not depend on any of the four front ends. Different teams own different use cases, so one interactor per use case keeps their changes apart. The nightly reminders are another driver in the outer ring that calls a use case. Possibly drop separate input boundaries for use cases only one front end calls, and use the push form only where it pays, such as progress for the batch.
- Layers, or a single module. It is create, read, update, delete with one validation rule and one front end. Interactors would pass data through, and request models would copy form fields one to one. A thin service with the name check, behind the web handler, and a data-access class is enough. If a second front end or real rules appear, extract a core then; the requirement will show where the boundary goes.
Summary
Section titled “Summary”- The dependency rule is the core of clean architecture: source dependencies point only inward, from frameworks and drivers through interface adapters and use cases to entities.
- The hexagonal version already obeys it. Clean architecture adds one interactor per use case, input boundaries, request and response models with no entity types, and a controller and presenter split.
- Sort a function by what it knows: syntax to the controller, wording to the presenter, sequence to the interactor, policy to the entity, technology to a gateway adapter.
- Per-use-case constructors make each use case’s dependencies, and whether it may write, visible and checked by the compiler.
- Returning a response is the better C++ default; an output boundary pays when a use case has zero, several, or later results.
- CMake libraries per ring make the build enforce the rule; each ring is tested alone.
- For a small program with one interface, the ceremony costs more than it returns. Choose it for many use cases, several delivery mechanisms, and a long life.