Hexagonal architecture (ports and adapters)
What you will learn on this page
Section titled “What you will learn on this page”- What hexagonal architecture, also called ports and adapters, is: a core that holds the rules and the use cases, and adapters around it that connect it to people and technology.
- The difference between a driving port, through which the outside world asks the core to do something, and a driven port, through which the core asks the outside world for something.
- Why the core owns its ports, and why they are written in the core’s terms rather than a technology’s.
- Why the storage port here hands out copies (find, change, save), what that costs, and one C++ lifetime trap it brings.
- How one CMake library per port stops a driving adapter from seeing the domain at all, and how a test proves it.
- How to test the core with in-memory adapters, every storage adapter with one contract test, and the console with a fake core.
- When the extra interfaces pay for themselves, and when they do not.
The problem the layered version left
Section titled “The problem the layered version left”The layered version moved the rules into a domain layer and the use
cases into an application layer. One coupling was left: the
application’s EnrollmentService holds pointers to MemoryStore and
MailOutbox, two concrete infrastructure classes. It only
declares them in its header, so the build is fast and the direction is
right, but three things still follow from naming them:
- Testing the use cases needs the real infrastructure. A test that
wants to check “a refused request sends no message” must build a
real
MailOutboxwith a stream and read the text back. - A database means editing the application. Replacing
MemoryStorewith a database class changes the service’s members, its header, and every test that builds it. - Nothing says what the application needs.
MemoryStorehas whatever functions its author wrote. Which of them the use cases depend on, and what each must promise, is written nowhere.
The dependency inversion page shows the fix for one dependency: let the policy own an interface and let the detail implement it. Hexagonal architecture applies that fix to every connection between the program’s rules and the outside world, on both sides, and gives the parts names.
The core, the ports, and the adapters
Section titled “The core, the ports, and the adapters”The design has three kinds of part.
- The core holds everything the program is about: the domain
(
domain::Courseand its seat rules) and the use cases (EnrollmentService). It knows nothing about consoles, streams, files, or databases. - Ports are interfaces the core owns, written in the core’s terms. They are the only ways in and out.
- Adapters sit outside the core. Each one translates between a port and one technology: text commands, an output stream, a map in memory, and, later, a database.
Ports come in two kinds, named by who starts the conversation:
| Kind | Who calls whom | Here | Also called |
|---|---|---|---|
| Driving (in) | An adapter calls the core to make it do something | EnrollmentUseCases |
primary |
| Driven (out) | The core calls an adapter to get something done | CourseStore, StudentRegister, Notifier |
secondary |
The console is a driving adapter: it drives the core. The in-memory course store is a driven adapter: the core drives it. Tests drive the core too, which is why they need no special access.
The hexagon in the name is only a drawing. Six sides give room to draw several ports; nothing in the design depends on the number six.
Text description of the diagram
A component diagram in three groups, left to right. The driving adapters group holds the Console, which reads text commands, run_cli, which runs one command and returns an exit status, and the tests. Each of them calls EnrollmentUseCases, the driving port, in the core group. The core group also holds EnrollmentService, which implements the driving port, uses domain::Course for the seat rules, and calls three driven ports: CourseStore, StudentRegister, and Notifier. The driven adapters group on the right holds MemoryCourses, MemoryStudents, and StreamNotifier, which implement CourseStore, StudentRegister, and Notifier. Every arrow that crosses into the core points at a port the core owns; no arrow leaves the core towards an adapter.
Diagram source (Mermaid)
flowchart LR
subgraph Driving["driving adapters"]
Con["Console<br/>text commands"]
Cli["run_cli<br/>one command, exit status"]
Tst["tests"]
end
subgraph Core["core"]
UC["EnrollmentUseCases<br/>driving port"]
Svc["EnrollmentService<br/>use cases"]
Dom["domain::Course<br/>seat rules"]
CS["CourseStore<br/>driven port"]
SR["StudentRegister<br/>driven port"]
NT["Notifier<br/>driven port"]
end
subgraph Driven["driven adapters"]
MC["MemoryCourses"]
MS["MemoryStudents"]
SN["StreamNotifier"]
end
Con -->|calls| UC
Cli -->|calls| UC
Tst -->|calls| UC
Svc ==>|implements| UC
Svc -->|uses| Dom
Svc -->|calls| CS
Svc -->|calls| SR
Svc -->|calls| NT
MC ==>|implements| CS
MS ==>|implements| SR
SN ==>|implements| NTThe arrows are the point of the drawing. Every dependency points
into the core. The driving adapters depend on the driving port; the
driven adapters depend on the driven ports; the core depends on
neither kind of adapter. A call still goes out from the core to the
store, but the dependency, the #include, goes in.
Step 1: sort the classes, members, and functions
Section titled “Step 1: sort the classes, members, and functions”Before writing code, sort what the layered version has. For each class, ask: is it about the problem, or about a technology? If it is about a technology, does the core call it, or does it call the core?
| Layered version | Hexagonal version | Kind | Why |
|---|---|---|---|
domain::Course |
domain::Course |
core: domain | The seat and waitlist rules are the problem itself. |
application::EnrollmentService |
core::EnrollmentService |
core: use cases | It runs each use case; it no longer names a technology. |
| its public functions | core::EnrollmentUseCases |
core: driving port | The console and the CLI need the use cases, not the class that implements them. |
MemoryStore’s course functions |
core::CourseStore |
core: driven port | What the use cases need from storage, stated once. |
MemoryStore’s student functions |
core::StudentRegister |
core: driven port | A different question, so a different port; see below. |
MailOutbox::send |
core::Notifier |
core: driven port | The core decides that a student is told and what the text says. |
MemoryStore |
MemoryCourses, MemoryStudents |
driven adapters | Maps in memory are one technology for storage. |
MailOutbox |
StreamNotifier |
driven adapter | Writing a line to a stream is one technology for delivery. |
presentation::Console |
adapters::Console |
driving adapter | Parsing text and wording replies is one technology for asking. |
Then sort inside each class:
- Data members that are state the rules depend on (seated students, the waitlist, capacity) belong to the domain. Data members that are handles to the outside (a stream, a map that stands in for a table) belong to adapters. The core’s only data members that point outward are pointers to ports.
- Functions that decide (may this student have a seat?) are domain
functions. Functions that sequence a use case (check the
student, ask the course, save, notify) are core use-case functions.
Functions that translate (parse
"enroll S1 CS101", format"ok: S1 enrolled in CS101", copy a course into a map) are adapter functions.
The student functions get their own port because the use cases ask two different questions of two different kinds of record. A database might keep them in one place today; a university that moves student records to a separate system tomorrow then changes one adapter. Splitting by question is the interface segregation principle applied to ports.
The driving port
Section titled “The driving port”The driving port is everything the outside world can ask the core to do. Its results are written in the use cases’ own terms, so a driving adapter 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 use cases' own terms, so a driving adapter never// needs a domain type. Everything here is built from plain standard// types (enums, std::size_t, std::string, std::vector), which is why// this header includes no domain header at all: a student id is just a// std::string on this side of the port.//// Each `enum class` lists every answer a use case can give. The names// stay inside the type (you write AddCourseResult::added), and an enum// class never turns into an int by accident.//// add_course: added, or refused because the code is taken or the// capacity is below 1.enum class AddCourseResult { added, already_exists, invalid_capacity };// add_student: added, or refused because the id is taken.enum class AddStudentResult { added, already_exists };
// enroll: the first two are successes (the course changed); the other// four are refusals, after which nothing changed and nobody was told.enum class EnrollStatus { seated, waitlisted, already_seated, already_waitlisted, no_such_student, no_such_course,};// What enroll hands back: the status, plus a number that only means// something for `waitlisted`. The `= ...` defaults just give every field// a value; the service always sets both when it returns one.struct EnrollResult { EnrollStatus status = EnrollStatus::no_such_course; std::size_t position = 0; // place on the waitlist, from 1, when waitlisted};
// drop: left_seat and left_waitlist are successes. not_in_course is a// refusal for a student who holds neither a seat nor a waitlist place.// The service does not look the student up, so an id nobody registered// gets not_in_course too, not a "no such student" answer.enum class DropStatus { left_seat, left_waitlist, not_in_course, no_such_course };struct DropResult { DropStatus status = DropStatus::no_such_course; // std::optional: either holds a student id or is empty. It is set // only when a seat was freed and someone on the waitlist took it. std::optional<std::string> promoted; // who took the freed seat, if anyone};
// One student in a report: the id and the name to print. A plain pair// of strings, rather than domain::Student, keeps the domain out of the// driving adapters.struct StudentLine { std::string id; std::string name;};
// A snapshot of one course for display. It is a copy, filled in by the// service; changing it changes nothing in the store. `seated` is in// enrollment order, and `waitlist` is first in line first.struct CourseReport { std::string code; std::string title; int capacity = 0; std::vector<StudentLine> seated; std::vector<StudentLine> waitlist;};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The driving port: what the outside world can ask the core to do.// Driving adapters, such as the console, depend on this and nothing// else in the core.//// It is an interface: a class with only pure virtual functions (the// `= 0` means "no body here; a derived class must supply one"). The// core's EnrollmentService is the real implementation, and a test can// supply a fake one. A caller holds an EnrollmentUseCases& and never// learns which it is talking to. Every function takes plain values (strings,// and an int capacity) and returns one of the results above; none of them throws for a refused// request, because a refusal is an expected answer, not an error.class EnrollmentUseCases {public: // Virtual, so destroying an implementation through a pointer to this // interface runs the implementation's destructor too. virtual ~EnrollmentUseCases() = default;
// Adds a course with `capacity` seats. Refuses a capacity below 1 and // a code that is already taken. virtual AddCourseResult add_course(const std::string& code, int capacity, const std::string& title) = 0; // Registers a student. Refuses an id that is already taken. virtual AddStudentResult add_student(const std::string& id, const std::string& name) = 0; // Gives `student` a seat in `course`, or a place at the back of its // waitlist when every seat is taken. Both ids are checked first. virtual EnrollResult enroll(const std::string& student, const std::string& course) = 0; // Takes `student` out of `course`. Leaving a seat hands it to the // first student on the waitlist, if there is one. virtual DropResult drop(const std::string& student, const std::string& course) = 0; // A snapshot of `course`, or an empty optional (std::nullopt) if // there is no such course. `const`: asking for a report changes // nothing. virtual std::optional<CourseReport> report(const std::string& course) const = 0;
protected: // Protected, not public: only derived classes can construct or copy // the interface part, so code holding an EnrollmentUseCases& cannot // copy just the base and slice off the rest. The idiom reference on // the "Reading the examples" page covers this form of interface. EnrollmentUseCases() = default; EnrollmentUseCases(const EnrollmentUseCases&) = default; EnrollmentUseCases& operator=(const EnrollmentUseCases&) = default;};The interface follows the site’s usual form. The destructor is
public and virtual, so an owner could delete through the interface.
The copy operations are protected: a derived class can still be
copied, but code that holds only an EnrollmentUseCases& cannot copy
the base part by accident and slice off the rest.
The driven ports
Section titled “The driven ports”A driven port states what the core needs, in the core’s terms. The
course store trades in domain::Course, not rows, keys, or SQL:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A driven port: what the core needs from storage, in the core's terms.// The core owns this interface; storage adapters implement it.//// It trades in copies, not pointers into the store, so that an adapter// for a database, which cannot hand out pointers into its tables, can// implement it too. The core finds a course, changes the copy, and// saves it.//// Unlike the driving port, this header includes course.hpp: a driven// port speaks the core's own language, domain::Course, because only the// core and its storage adapters ever see it.class CourseStore {public: virtual ~CourseStore() = default;
// Returns false, and stores nothing, if the code is taken. Takes the // course by const reference: the adapter keeps whatever copy it // needs, and the caller's object is left as it was. virtual bool add(const domain::Course& course) = 0; // A copy of the stored course, or nothing if there is none. The // std::optional is empty (std::nullopt) for an unknown code. `const`: // looking a course up changes nothing in the store. virtual std::optional<domain::Course> find(const domain::CourseCode& code) const = 0; // Stores `course`, replacing the one with the same code. An adapter // that can fail to write, such as a database, reports it by throwing. // This is the moment a change made to a copy from find becomes real; // a use case that forgets to call it loses the change. virtual void save(const domain::Course& course) = 0;
// As in the driving port: protected, so only an adapter can copy or // build the interface part, and nobody slices an adapter by copying // a CourseStore&.protected: CourseStore() = default; CourseStore(const CourseStore&) = default; CourseStore& operator=(const CourseStore&) = default;};The notifier knows only who is told and what they are told:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A driven port for telling a student something. The core decides that// a student is told and what the message says; the adapter decides how// it is delivered.class Notifier {public: virtual ~Notifier() = default;
// Tells student `to` the message `text`. std::string_view is a // read-only view of characters that someone else owns; here, a // string the use case built for this call. It is valid only until // notify returns, so an adapter that keeps the message for later // (a queue, or the tests' recorder) must copy it into a std::string. virtual void notify(const domain::StudentId& to, std::string_view text) = 0;
protected: Notifier() = default; Notifier(const Notifier&) = default; Notifier& operator=(const Notifier&) = default;};Both headers live in core/driven/. That location is the meaning of
“the core owns its ports”: when the core needs something new, the
core’s authors change the port, and the adapters follow. An adapter
never adds a function to a port because its technology happens to
offer one.
Why the store hands out copies
Section titled “Why the store hands out copies”find returns std::optional<domain::Course>: a copy, or
nothing. The use case changes the copy and calls save. The layered
version’s MemoryStore handed out pointers into its map instead, so
why change?
- A database cannot hand out pointers into its tables. It reads a
row and builds an object. A port that returns
Course*could only be implemented by an adapter that keeps every course in memory, and the port would quietly promise that the pointer stays valid. - The store must know when something changed. With a pointer, the
core changes the stored course directly, and a database adapter has
no moment at which to write it.
saveis that moment. - The order of effects becomes visible. The use case saves before it notifies, so nobody is told about a change that was lost.
The choice has costs. Each command that changes a course copies it
twice, once out of the store and once back in, with its seated vector
and waitlist; report copies it once. That is small for a course of a
few hundred students, and small next to a database read, but these are
copies the pointer version did not make; they have not been measured
here. A use
case that forgets save loses the change silently, which only a
test catches. And two callers that each find, change, and save the
same course can overwrite each other’s change; the requirements
section below comes back to that.
Course behaves as a value type in the C++ sense, and that is
what makes copies safe: it owns all its members and refers to nothing
outside itself, so a copy is a complete, independent course. It still
has an identity, its code, which is how save knows which stored
course a copy replaces.
The core: use cases that name no adapter
Section titled “The core: use cases that name no adapter”EnrollmentService implements the driving port and holds three
pointers to driven ports. It names no adapter, so it compiles and is
tested without any storage or delivery code:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The use cases. They implement the driving port and use only the// driven ports, so the core names no adapter: it compiles, and is// tested, without any storage or delivery code.//// `final`: nothing may derive from it. `public EnrollmentUseCases`: it// is a driving-port implementation, so a Console can be handed one.class EnrollmentService final : public EnrollmentUseCases {public: // All three must outlive the service. The constructor takes // references (so nobody can pass a null) and keeps their addresses // (`&courses` is "the address of courses"). The service borrows the // adapters; whoever created them, `main` here, still owns them. EnrollmentService(CourseStore& courses, StudentRegister& students, Notifier& notifier) : courses_{&courses}, students_{&students}, notifier_{¬ifier} {}
// `override` asks the compiler to check that each of these really // replaces a virtual function of the driving port.
AddCourseResult add_course(const std::string& code, int capacity, const std::string& title) override; AddStudentResult add_student(const std::string& id, const std::string& name) override; EnrollResult enroll(const std::string& student, const std::string& course) override; DropResult drop(const std::string& student, const std::string& course) override; std::optional<CourseReport> report(const std::string& course) const override;
private: // Only port types: the service never names MemoryCourses or any // other adapter, so it compiles without them. CourseStore* courses_; // non-owning, never null StudentRegister* students_; // non-owning, never null Notifier* notifier_; // non-owning, never null};The pointers are non-owning: main owns the adapters, and the
constructor’s comment states the lifetime rule. They are pointers
rather than references so that the class could be assignable; a
reference member would delete the copy assignment operator. The
service is final because nothing should specialise the use cases by
inheritance; a different behaviour comes from a different adapter.
enroll follows the shape every use case here has: ask, let the
domain decide, keep, tell.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// One use case: enroll `student` in `course`. The shape is "ask, let the// domain decide, keep, tell":// ask: look up the student and the course through the driven ports;// decide: the course copy applies the seat and waitlist rules;// keep: save the changed copy back through the CourseStore port;// tell: send the student a message through the Notifier port.// A refusal returns at once with a status, before anything is saved or// sent. If an adapter throws (a save that fails, say), the exception// leaves this function; nothing here catches it.EnrollResult EnrollmentService::enroll(const std::string& student, const std::string& course) { // find returns an optional Student; `!` is true when it is empty. The // student record itself is not needed, only the fact that it exists. // `return {EnrollStatus::no_such_student, 0};` builds an EnrollResult // from its two fields, in order: status, then position. if (!students_->find(student)) return {EnrollStatus::no_such_student, 0}; // A copy of the stored course, owned by this function. Changing it // does not change the store until save is called. std::optional<domain::Course> found = courses_->find(course); // a copy if (!found) return {EnrollStatus::no_such_course, 0};
// `found->` reaches the Course inside the optional. The domain, not // the service, decides between a seat, the waitlist, or a refusal. const domain::EnrollOutcome outcome = found->enroll(student); // the domain decides // Translate the domain's answer into the driving port's answer, and // do the saving and telling only for the two answers that changed // the course. Each case ends in `return`, so no case falls through. switch (outcome.kind) { case domain::EnrollOutcome::Kind::seated: // `*found` is the changed Course itself. course_name, a helper // above, gives "<code> <title>", such as "CS101 Software Design". courses_->save(*found); // save first: nobody is told about a change that was lost notifier_->notify(student, "you have a seat in " + course_name(*found)); return {EnrollStatus::seated, 0}; case domain::EnrollOutcome::Kind::waitlisted: courses_->save(*found); // std::to_string turns the number into text, such as "1". notifier_->notify(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: // nothing changed, nothing to save return {EnrollStatus::already_seated, 0}; case domain::EnrollOutcome::Kind::already_waitlisted: return {EnrollStatus::already_waitlisted, 0}; } return {EnrollStatus::no_such_course, 0}; // not reached: every kind is handled above}// `found`, the copy, is destroyed when the function returns, on every// path. The store keeps its own course, which save replaced if the// enrollment changed it.How this code works: One enroll request through the hexagon
Follow the script’s line enroll S3 CS101. CS101 has 2 seats, and S1
and S2 already hold them.
mainto the console.maincallsconsole.run("enroll S3 CS101"). The console, a driving adapter, splits the line into the wordsenroll,S3,CS101, and the first word sends it to its privateenrollhelper. The helper sees exactly three words and callsuse_cases.enroll("S3", "CS101").- Across the first boundary.
use_casesis anEnrollmentUseCases&, so this is a virtual call; it lands inEnrollmentService::enroll. Only two strings cross, and only anEnrollResultwill come back. The console never sees a course. - Ask.
students_->find("S3")goes through theStudentRegisterport toMemoryStudents, which has S3, so the check passes. Thencourses_->find("CS101")goes through theCourseStoreport toMemoryCourses, which copies the stored course out of its map. That copy,found, belongs to this call ofenroll: seated S1 and S2, waitlist empty. - Decide.
found->enroll("S3")runs the domain rules on the copy. S3 is not seated and not waiting, and 2 seats out of 2 are taken, so S3 goes to the back of the waitlist. The answer iswaitlisted, position 1. The store still holds the old course. - Keep.
courses_->save(*found)hands the changed copy back, andMemoryCoursesreplaces its stored course with a copy of it. - Tell.
notifier_->notify("S3", ...)goes through theNotifierport toStreamNotifier, which writesnotify S3: you are number 1 on the waitlist for CS101 Software Designtostd::cout. This is why that line is printed before the reply. - Back out.
enrollreturnswaitlistedwith position 1, andfoundis destroyed. The console turns the result intook: S3 waitlisted for CS101 (position 1), andmainprints it.
Who owns what. main owns all five objects (the two stores, the
notifier, the service, the console) as local variables. The service
and the console only hold pointers to what they were given. Each
store owns its records by value, and enroll owns its copy for the
length of one call.
The six enroll lines before the first drop, in order (capacity 2):
| Command | Seated before | Waitlist before | Domain answer | Saved and told? | Reply |
|---|---|---|---|---|---|
enroll S1 CS101 |
none | none | seated |
yes | ok: S1 enrolled in CS101 |
enroll S2 CS101 |
S1 | none | seated |
yes | ok: S2 enrolled in CS101 |
enroll S3 CS101 |
S1, S2 | none | waitlisted, 1 |
yes | ok: S3 waitlisted for CS101 (position 1) |
enroll S4 CS101 |
S1, S2 | S3 | waitlisted, 2 |
yes | ok: S4 waitlisted for CS101 (position 2) |
enroll S3 CS101 |
S1, S2 | S3, S4 | already_waitlisted |
no | refused: S3 is already on the waitlist for CS101 |
enroll S9 CS101 |
S1, S2 | S3, S4 | not asked | no | refused: no student S9 |
For S9 the service stops at step 3: the student check fails, so the course is never even loaded.
The refused cases (already_seated, already_waitlisted) change
nothing, so they save nothing and tell no one. The return after the
switch is there because GCC’s -Wreturn-type cannot assume an
enum class holds only its listed values.
Text description of the diagram
A sequence diagram for one enroll command. The console, a driving adapter, asks EnrollmentService to enroll S3 in CS101. The service asks the StudentRegister port to find S3 and gets a student back. It asks the CourseStore port to find CS101 and gets a copy of the course. It asks that copy, a domain object, to enroll S3, and the course answers waitlisted, position 1. The service then saves the changed copy through the CourseStore port, and only after that notifies S3 through the Notifier port that they are number 1 on the waitlist. Finally it returns “waitlisted, position 1” to the console, which formats the reply text. The service never learns which adapters sit behind the three ports.
Diagram source (Mermaid)
sequenceDiagram
participant C as Console, driving adapter
participant S as EnrollmentService, core
participant R as StudentRegister port
participant K as CourseStore port
participant D as Course copy, domain
participant N as Notifier port
C->>S: enroll S3 in CS101
S->>R: find S3
R-->>S: a student
S->>K: find CS101
K-->>S: a copy of the course
S->>D: enroll S3
D-->>S: waitlisted, position 1
S->>K: save the changed copy
S->>N: notify S3, number 1 on the waitlist
S-->>C: waitlisted, position 1
Note over C: formats the reply textThe adapters
Section titled “The adapters”A driven adapter implements a driven port with one technology. The
in-memory course store keeps a map, and find returns a copy of the
stored course:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A driven adapter: the course store kept in memory. The program uses// it today, and the core's tests use it because it is fast and needs// no setup. A database adapter would implement the same port.//// It lives outside the core (namespace adapters) and depends on the// core's port, never the other way round: the core does not know this// class exists. `final` and `override` as in the service.class MemoryCourses final : public core::CourseStore {public: bool add(const domain::Course& course) override; std::optional<domain::Course> find(const domain::CourseCode& code) const override; void save(const domain::Course& course) override;
private: // The stored courses, looked up by code. The map owns each Course by // value, so the store's courses live exactly as long as the store. std::map<domain::CourseCode, domain::Course> courses_;};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
#include "memory_courses.hpp"
namespace adapters {
// The whole adapter is three short translations from the port's promises// to std::map calls. No rule about seats or waitlists appears here.
// try_emplace(key, value) inserts a copy of `course` only if no course// has that code yet; if the code is taken it changes nothing. It returns// a pair: an iterator to the entry, and a bool that is true only if it// inserted. `.second` is that bool, which is exactly what add promises.bool MemoryCourses::add(const domain::Course& course) { return courses_.try_emplace(course.code(), course).second;}
// map::find returns an iterator: either one pointing at the entry, or// end() if the code is not there. For a found entry, `found->second` is// the stored Course (`first` is the key). Returning it builds an// optional holding a copy, so the caller can change what it gets back// without touching the map.std::optional<domain::Course> MemoryCourses::find(const domain::CourseCode& code) const { const auto found = courses_.find(code); if (found == courses_.end()) return std::nullopt; return found->second; // a copy: changing it does not change the store}
// insert_or_assign replaces the course stored under this code with a// copy of `course`. If the code was never added, it inserts it instead;// the port does not say what save should do then, and the contract test// does not check it. A map in memory cannot fail to write, so this save// never reports a failure.void MemoryCourses::save(const domain::Course& course) { courses_.insert_or_assign(course.code(), course);}
} // namespace adaptersStreamNotifier stands in for an email gateway and writes each
message as one line to a stream that main lends it; MemoryStudents
keeps the students in a second map.
A driving adapter turns something from the outside into calls on the
driving port. The console is the layered version’s presentation code
with one change: it holds a core::EnrollmentUseCases* instead of the
concrete service.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A driving adapter: the registrar's console. It turns a command line// into one call on the driving port, and the result into a reply. It// sees only the port, so it can be tested with a fake core.//// Its only include from the core is enrollment_use_cases.hpp, the// driving port, so it cannot name a Course, a store, or the service.class Console {public: // `use_cases` must outlive the console. The console borrows it and // keeps its address. `explicit` stops a stray conversion from // turning a use-cases object into a Console without anyone asking. explicit Console(core::EnrollmentUseCases& use_cases) : use_cases_{&use_cases} {}
// Runs one command line and returns the reply, "ok: ..." or "refused: ...". // The line is split into words; the first word picks one call on the // port (course, student, enroll, drop, or report), and that call's // result is turned into text. A line with the wrong number of words, // or an unknown command, is refused here, without calling the core. std::string run(std::string_view line);
private: core::EnrollmentUseCases* use_cases_; // non-owning, never null};Every adapter here is an instance of the Adapter pattern: it gives one interface the shape another one expects. The architecture is a decision about where those adapters go and which way their dependencies point.
class core::EnrollmentUseCases
driving port, abstract
Member functions
virtual EnrollResult enroll(const std::string& student, const std::string& course) = 0;virtual DropResult drop(const std::string& student, const std::string& course) = 0;virtual std::optional<CourseReport> report(const std::string& course) const = 0;
class core::EnrollmentService
core, final, implements EnrollmentUseCases
Data members
CourseStore* courses_;non-owning, never nullStudentRegister* students_;non-owning, never nullNotifier* notifier_;non-owning, never null
Member functions
EnrollResult enroll(const std::string& student, const std::string& course) override;DropResult drop(const std::string& student, const std::string& course) override;
class domain::Course
core: domain, value type
Data members
std::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);
class core::CourseStore
driven port, abstract
Member functions
virtual bool add(const domain::Course& course) = 0;virtual std::optional<domain::Course> find(const domain::CourseCode& code) const = 0;virtual void save(const domain::Course& course) = 0;
class core::StudentRegister
driven port, abstract
Member functions
virtual bool add(const domain::Student& student) = 0;virtual std::optional<domain::Student> find(const domain::StudentId& id) const = 0;
class core::Notifier
driven port, abstract
Member functions
virtual void notify(const domain::StudentId& to, std::string_view text) = 0;
class adapters::MemoryCourses
driven adapter, implements CourseStore
Data members
std::map<domain::CourseCode, domain::Course> courses_;
class adapters::MemoryStudents
driven adapter, implements StudentRegister
Data members
std::map<domain::StudentId, domain::Student> students_;
class adapters::StreamNotifier
driven adapter, implements Notifier
Data members
std::ostream* out_;non-owning, never null
class adapters::Console
driving adapter
Data members
core::EnrollmentUseCases* use_cases_;non-owning, never null
Member functions
std::string run(std::string_view line);
The composition root
Section titled “The composition root”main is the only code that names adapters. It creates the driven
adapters first, then the core that borrows them, then the driving
adapter that borrows the core, so every borrower is destroyed before
what it borrows:
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. // An array of std::string_view, each a view of a string literal. // Literals live for the whole program, so the views never dangle. 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 composition root: the only place that chooses adapters. Driven // adapters first, then the core that uses them, then the driving // adapter that uses the core. // `main` owns all five objects, as plain local variables: no new, no // smart pointers. Each later object borrows earlier ones by reference. adapters::MemoryCourses courses; adapters::MemoryStudents students; adapters::StreamNotifier notifier{std::cout}; // messages go to the screen // The service sees the three adapters only as its three ports. core::EnrollmentService service{courses, students, notifier}; // The console sees the service only as the driving port. adapters::Console console{service};
for (const std::string_view line : script) { std::cout << "> " << line << '\n'; // The notifier writes to std::cout while run is still working, so // a "notify ..." line appears before this command's reply. const std::string reply = console.run(line); // may print notifications first std::cout << reply << '\n'; }} // destroyed in reverse: console, service, notifier, students, coursesSwapping the in-memory store for a database is a change to these lines and a new adapter library. The core and the console do not change.
Making the build enforce the sides
Section titled “Making the build enforce the sides”Each part is its own CMake library, and each library links only what its side may see:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
# The core: the domain, the ports it owns, and the use cases. Nothing in# the core links an adapter.add_library(arch_hex_domain STATIC core/domain/course.cpp)target_include_directories(arch_hex_domain PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/core/domain)
# The driving port: header only, and free of domain types.add_library(arch_hex_driving_port INTERFACE)target_include_directories(arch_hex_driving_port INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/core/driving)
# The driven ports: header only; they name domain types.add_library(arch_hex_driven_ports INTERFACE)target_include_directories(arch_hex_driven_ports INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/core/driven)target_link_libraries(arch_hex_driven_ports INTERFACE arch_hex_domain)
add_library(arch_hex_core STATIC core/service/enrollment_service.cpp)target_include_directories(arch_hex_core PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/core/service)target_link_libraries(arch_hex_core PUBLIC arch_hex_driving_port arch_hex_driven_ports)
# Adapters: one library each. A driven adapter sees only the driven# ports; a driving adapter sees only the driving port.add_library(arch_hex_memory STATIC adapters/memory/memory_courses.cpp adapters/memory/memory_students.cpp)target_include_directories(arch_hex_memory PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/adapters/memory)target_link_libraries(arch_hex_memory PUBLIC arch_hex_driven_ports)
add_library(arch_hex_stream STATIC adapters/stream/stream_notifier.cpp)target_include_directories(arch_hex_stream PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/adapters/stream)target_link_libraries(arch_hex_stream PUBLIC arch_hex_driven_ports)
add_library(arch_hex_console STATIC adapters/console/console.cpp)target_include_directories(arch_hex_console PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/adapters/console)target_link_libraries(arch_hex_console PUBLIC arch_hex_driving_port)
add_library(arch_hex_cli STATIC adapters/cli/cli.cpp)target_include_directories(arch_hex_cli PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/adapters/cli)target_link_libraries(arch_hex_cli PUBLIC arch_hex_driving_port)
# main is the composition root: it picks one adapter for each port.lld_add_example(arch_enrollment_hexagonal SOURCES main.cpp EXPECTED_OUTPUT expected_output.txt)target_link_libraries(arch_enrollment_hexagonal PRIVATE arch_hex_console arch_hex_core arch_hex_memory arch_hex_stream)
lld_add_test(arch_hex_core_tests SOURCES tests/test_core.cpp)target_link_libraries(arch_hex_core_tests PRIVATE arch_hex_core arch_hex_memory)
lld_add_test(arch_hex_course_store_contract SOURCES tests/test_course_store_contract.cpp)target_link_libraries(arch_hex_course_store_contract PRIVATE arch_hex_memory)
lld_add_test(arch_hex_console_tests SOURCES tests/test_console.cpp)target_link_libraries(arch_hex_console_tests PRIVATE arch_hex_console)
lld_add_test(arch_hex_cli_tests SOURCES tests/test_cli.cpp)target_link_libraries(arch_hex_cli_tests PRIVATE arch_hex_cli arch_hex_core arch_hex_memory arch_hex_stream)
# A file that includes the domain header, built with only the driving# port, as a driving adapter is. It is not part of the normal build; the# test builds it and expects the compiler to report a missing header.add_executable(arch_hex_driving_adapter_violation EXCLUDE_FROM_ALL checks/driving_adapter_uses_domain.cpp)target_link_libraries(arch_hex_driving_adapter_violation PRIVATE arch_hex_driving_port)add_test(NAME arch_hex_driving_adapter_cannot_see_domain COMMAND ${CMAKE_COMMAND} --build ${CMAKE_BINARY_DIR} --target arch_hex_driving_adapter_violation)set_tests_properties(arch_hex_driving_adapter_cannot_see_domain PROPERTIES PASS_REGULAR_EXPRESSION "course.hpp.*(No such file or directory|file not found)" LABELS "test")Read the links as a table of who can include what:
| Library | Can include | Cannot include |
|---|---|---|
arch_hex_domain |
the domain | ports, service, adapters |
arch_hex_core |
domain, all ports, service | any adapter |
arch_hex_memory, _stream |
domain, driven ports | driving port, service, other adapters |
arch_hex_console, _cli |
the driving port | domain, driven ports, service |
The driving adapters are the strictest. The driving port’s headers
name no domain type, so the console’s library does not need the
domain’s include directory, and does not get it. A console that
includes course.hpp by name fails to compile. That claim is tested:
arch_hex_driving_adapter_cannot_see_domain builds a file that
includes course.hpp with only the driving port linked, and passes
only if the compiler reports the header missing. The check controls
only include paths, so a relative path such as
../../core/domain/course.hpp would get past it; review, or an
include check like the one on the
modular monolith page, must catch
that.
The core links no adapter, so a core that included
memory_courses.hpp would fail to compile too. The build cannot
catch everything: an adapter can still hold a rule (a console that
refuses capacities above 300), and a port can still be shaped like a
technology. Those need review, and the tests below.
Same behaviour, different structure
Section titled “Same behaviour, different structure”The hexagonal 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)A test checks that the text is identical to version 0’s. The
notification lines appear before each reply because the service
notifies before it returns, and main prints the reply only after
console.run returns.
Testing through the ports
Section titled “Testing through the ports”Ports give each part a seam, and the three kinds of test here use them differently.
The core, with in-memory adapters. The core tests drive the service through its driving port. They use the real in-memory stores, because they are fast and need no setup, and a notifier that records messages instead of writing them. No console, no text, and no output stream are involved:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The core is tested through its driving port, with in-memory driven// adapters and a notifier that records instead of sending. No console,// no text commands, no output stream.//// The test helpers come from the site's small test header, lld_test.hpp:// LLD_TEST(name) defines one test, LLD_CHECK(condition) records a// failure if the condition is false, and LLD_CHECK_EQ(actual, expected)// records a failure, and prints both values, unless they are equal.//// namespace { ... } with no name keeps these helpers private to this file.namespace {
// A test double for the Notifier port: instead of delivering a message,// it writes it down, so a test can ask afterwards who was told what.// A struct's members and base class are public by default.struct RecordingNotifier final : core::Notifier { std::vector<std::pair<std::string, std::string>> sent; // (to, text) void notify(const domain::StudentId& to, std::string_view text) override { // emplace_back builds the (to, text) pair in place at the end of // the vector. std::string{text} copies the characters, because the // string_view is only valid during this call. sent.emplace_back(to, std::string{text}); }};
// A small composition root for one test: real in-memory stores, the// recording notifier, and the service wired to them. Members are built// in the order they are declared, so the three adapters exist before// `service` takes references to them; that order matters. Every test// starts from the same state: CS101 with ONE seat, and students S1 and// S2 registered. The constructor ignores the results; they are known.struct Office { adapters::MemoryCourses courses; adapters::MemoryStudents students; RecordingNotifier notifier; core::EnrollmentService service{courses, students, notifier};
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. The test then reads the store directly, not// the result, to prove the use case saved its change, and reads the// recorder to prove exactly one message went to S1.LLD_TEST(an_enrollment_is_saved_and_the_student_told) { Office office; LLD_CHECK(office.service.enroll("S1", "CS101").status == core::EnrollStatus::seated); const std::optional<domain::Course> stored = office.courses.find("CS101"); // `&&` stops early if `stored` is empty, so `->` is used only when a // course is really there. LLD_CHECK(stored && stored->seated() == std::vector<std::string>{"S1"}); // std::size_t{1} has the same unsigned type as size(), so the check // does not compare a signed number with an unsigned one. LLD_CHECK_EQ(office.notifier.sent.size(), std::size_t{1}); // `.first` of the recorded pair is who was told. LLD_CHECK_EQ(office.notifier.sent[0].first, std::string{"S1"});}
// S1 takes the only seat and S2 goes on the waitlist. When S1 drops, S2// must be promoted: in the result, in the store, and in the last// message sent (`.back()` is the newest entry; `.second` is its text).LLD_TEST(a_freed_seat_goes_to_the_first_waiting_student) { Office office; office.service.enroll("S1", "CS101"); office.service.enroll("S2", "CS101"); const core::DropResult dropped = office.service.drop("S1", "CS101"); LLD_CHECK(dropped.promoted == std::optional<std::string>{"S2"}); // find returns a temporary optional; using it and finishing with it in // one expression is safe, because it lives until the end of that line. LLD_CHECK(office.courses.find("CS101")->seated() == std::vector<std::string>{"S2"}); LLD_CHECK_EQ(office.notifier.sent.back().second, std::string{"a seat opened; you are enrolled in CS101 Software Design"});}
// Two refusals: S9 was never registered, and S1 is registered but holds// no seat or waitlist place in CS101. Afterwards the course is still// empty and the recorder holds no message: a refusal has no effects.LLD_TEST(a_refused_request_changes_and_sends_nothing) { Office office; LLD_CHECK(office.service.enroll("S9", "CS101").status == core::EnrollStatus::no_such_student); LLD_CHECK(office.service.drop("S1", "CS101").status == core::DropStatus::not_in_course); LLD_CHECK(office.courses.find("CS101")->seated().empty()); LLD_CHECK(office.notifier.sent.empty());}The tests read the store directly (office.courses.find("CS101")) to
check that the use case saved its change. A use case that forgot
save would fail the first test, even though its return value was
right.
Each storage adapter, with one contract test. A port is a
promise, and every adapter must keep it. The contract test states the
promise once, as a function that takes any CourseStore&:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// What every CourseStore adapter must do, written once. The in-memory// adapter runs it today; a database adapter would run the same checks.//// LLD_TEST(name) defines one test; LLD_CHECK(condition) records a// failure if the condition is false; LLD_CHECK_EQ(actual, expected)// records one, printing both values, unless they are equal. They come// from the site's test header, lld_test.hpp.namespace {
// Takes the port, CourseStore&, not any one adapter, so every adapter// can be passed in and held to the same promises. `store` must start// empty. Each step checks one sentence of the port's comments.void check_course_store_contract(core::CourseStore& store) { // add: true for a new code, false for a taken one. LLD_CHECK(store.add(domain::Course{"CS101", "Software Design", 1})); LLD_CHECK(!store.add(domain::Course{"CS101", "Another Title", 5})); // code taken // find: nothing for an unknown code. LLD_CHECK(!store.find("CS999").has_value());
// find: a copy. Enrolling S1 in the copy must leave the stored course // as it was. (Course::enroll's result is not needed here.) std::optional<domain::Course> copy = store.find("CS101"); LLD_CHECK(copy.has_value()); copy->enroll("S1"); LLD_CHECK(store.find("CS101")->seated().empty()); // a copy, until saved
// save: now the change is kept. The title check also shows that the // refused second add stored nothing: the course is still the first one. store.save(*copy); // Keep the returned copy in a variable: a reference into it, such as // title(), would dangle once the temporary optional is gone. const std::optional<domain::Course> saved = store.find("CS101"); LLD_CHECK(saved.has_value()); LLD_CHECK_EQ(saved->seated().size(), std::size_t{1}); LLD_CHECK_EQ(saved->title(), std::string{"Software Design"});}
} // namespace
// The only test today: run the contract on a fresh in-memory store. A// database adapter would add one more test like this, on an empty table.LLD_TEST(memory_courses_keeps_the_course_store_contract) { adapters::MemoryCourses store; check_course_store_contract(store);}How this code works: The contract test, step by step
The function keeps two things apart: the course in the store, and
copy, the course the test holds. Each step checks one promise.
| Step | Call | Stored CS101 | copy |
What it proves |
|---|---|---|---|---|
| 1 | add CS101, “Software Design”, 1 seat |
added, nobody seated | not made yet | add returns true for a new code |
| 2 | add CS101 again, “Another Title”, 5 seats |
unchanged | not made yet | add returns false for a taken code |
| 3 | find("CS999") |
unchanged | not made yet | find is empty for an unknown code |
| 4 | copy = find("CS101") |
nobody seated | nobody seated | find returns a course |
| 5 | copy->enroll("S1") |
nobody seated | S1 seated | the stored course did not change |
| 6 | save(*copy) |
S1 seated | S1 seated | (checked next) |
| 7 | saved = find("CS101") |
S1 seated | S1 seated | one seated, title “Software Design” |
Step 5 is the heart of it: changing what find returned does not
change the store. Step 7’s title check also confirms step 2: if the
refused add had replaced the course, the title would be “Another
Title”.
The test function takes a CourseStore&, so it cannot tell which
adapter it is checking. That is the point: the same function, called
with a database adapter on an empty table, holds that adapter to the
same steps.
A database adapter would call check_course_store_contract on a
fresh test database. If it passes, the core tests that use the
in-memory store also say something true about the database version,
because both keep the same promise. That is what makes testing the
core with in-memory adapters trustworthy rather than hopeful. It is
only as strong as the checks it contains: this one does not check
that capacity and the waitlist survive a round trip, what save does
with a code that was never added, or how a write failure is reported.
A promise the contract test does not check is still only hoped for.
The console, with a fake core. The console tests replace the whole core with a fake that returns fixed results. No rule runs, so each test checks only parsing and wording, and a test can ask for a result that would take several setup steps through the real core, such as position 3 on a waitlist:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The console adapter is tested with a fake core that returns fixed// results. No rules, storage, or notifications run, so each test// checks only parsing and reply wording.namespace {
// A fake core: it implements the whole driving port, but each function// just returns a fixed answer. enroll also writes down the ids it was// given, so a test can see what the console passed in. A parameter with// no name, such as `const std::string&` in add_course, is one the fake// ignores; leaving the name out says so and avoids an unused warning.struct FakeUseCases final : core::EnrollmentUseCases { // What enroll will answer: waitlisted at position 3, a result that // would take at least four enrollments through the real core. core::EnrollResult next_enroll{core::EnrollStatus::waitlisted, 3}; std::string last_student; // empty until enroll is called std::string last_course;
core::AddCourseResult add_course(const std::string&, int, const std::string&) override { return core::AddCourseResult::added; } core::AddStudentResult add_student(const std::string&, const std::string&) override { return core::AddStudentResult::added; } core::EnrollResult enroll(const std::string& student, const std::string& course) override { last_student = student; last_course = course; return next_enroll; } // Always "left the seat, and S7 was promoted"; the "S7" text becomes // the optional's string. core::DropResult drop(const std::string&, const std::string&) override { return {core::DropStatus::left_seat, "S7"}; } // Always an empty optional (std::nullopt): "there is no such course". std::optional<core::CourseReport> report(const std::string&) const override { return std::nullopt; }};
} // namespace
// LLD_TEST(name) defines one test, LLD_CHECK(condition) fails if the// condition is false, and LLD_CHECK_EQ(actual, expected) fails, printing// both, unless they are equal. They come from lld_test.hpp.//// The console must split "enroll S1 CS101" into the two ids, pass them// to the port, and word the fake's answers exactly as a user sees them.LLD_TEST(the_console_passes_the_words_and_formats_the_result) { FakeUseCases fake; adapters::Console console{fake}; LLD_CHECK_EQ(console.run("enroll S1 CS101"), std::string{"ok: S1 waitlisted for CS101 (position 3)"}); LLD_CHECK_EQ(fake.last_student, std::string{"S1"}); LLD_CHECK_EQ(fake.last_course, std::string{"CS101"}); LLD_CHECK_EQ(console.run("drop S1 CS101"), std::string{"ok: S1 dropped CS101; S7 moved from the waitlist"});}
// "enroll S1" has two words, not three, so the console answers with the// usage text itself; last_student still being empty proves the fake's// enroll was never called. "report CS101" is well formed and does reach// the fake's report, which answers "nothing"; the check shows how the// console words that answer.LLD_TEST(the_console_refuses_bad_input_without_calling_the_core) { FakeUseCases fake; adapters::Console console{fake}; LLD_CHECK_EQ(console.run("enroll S1"), std::string{"refused: usage: enroll <student> <course>"}); LLD_CHECK_EQ(console.run("report CS101"), std::string{"refused: no course CS101"}); LLD_CHECK(fake.last_student.empty());}The fake implements every function of the driving port, including ones the tests do not use. A large driving port makes every fake large, which is one more reason to keep ports small. The test-doubles page covers fakes, stubs, and mocks in detail.
Hexagonal and layered, side by side
Section titled “Hexagonal and layered, side by side”| Question | Layered version | Hexagonal version |
|---|---|---|
| Who depends on storage? | The application names MemoryStore |
The core owns CourseStore; the adapter implements it |
| Where are the interfaces? | None between application and infrastructure | One per port, in the core |
| Testing the use cases | With the real infrastructure classes | With any adapters, or recording fakes |
| Testing the console | With the real application | With a fake core |
| Adding a database | Change the application’s members and header | Add an adapter; change main |
| Cost | Fewer files and no virtual calls | Four interfaces, and a course copied out and back per change |
The two are not rivals. The hexagonal core still has layers inside it (domain below use cases), and the layered version already had the right direction between application and domain. Hexagonal architecture changes the edges: everything outside the core becomes a replaceable adapter behind an interface the core owns.
When hexagonal architecture fits, and when it does not
Section titled “When hexagonal architecture fits, and when it does not”It fits when:
- The rules outlive the technology. Enrollment rules change rarely; the user interface, the storage, and the mail service are each likely to be replaced during the program’s life.
- There is more than one adapter per port, now or soon: a console and a CLI, or an in-memory store for tests and a database for production.
- The core is worth testing on its own, quickly and without infrastructure, because it holds real decisions.
It does not fit, or not yet, when:
- There are no rules. A program that copies rows from a form to a table has nothing for a core to own. The ports would pass data through unchanged.
- Each port will only ever have one adapter, and tests can use it. Every interface is then indirection without variation, which the cost of abstraction page warns about.
- The program is small and short-lived. Version 0, one file, was the right design for a script; this one is for a system that will change.
The costs are real but modest. Each port is a header to read and to
keep in step with its adapters. Each call through a port is a virtual
call; that is usually small next to the input and output the adapter
does, but it is not free, and it has not been measured here.
Debugging means stepping through an interface to find which adapter is
behind it, which main answers in one place. The save step, and the
copy it needs, is the price of a storage port a database could
implement.
Common mistakes
Section titled “Common mistakes”- Ports that copy the technology. A port with
query(sql)orget(key)andput(key, bytes)moves the#includewithout moving the knowledge. Shape ports by what the use cases ask. - Domain types leaking through the driving port. If
EnrollmentUseCases::reportreturned adomain::Course, every driving adapter would depend on the domain and could start applying its rules itself, for example checking for a free seat before callingenroll. Return use-case results. - Rules in adapters. A console that checks whether a course is
full before calling
enrollduplicates a domain rule, and the CLI will not have it. Adapters translate; the core decides. - One giant port. A
Repositorywith every query for every use case makes every fake and every adapter implement everything. Split by question. - Forgetting
save. With a copy-based store, the change is lost silently. Test it by reading the store, as the core tests do. - Notifying before saving. If
savethrows after the student has been told, the message is wrong. Save first. - Adapters that call each other. If
MemoryCoursescalled the notifier directly, a rule (who is told when) would move out of the core. Adapters talk only to their port. - Interfaces for things that never vary. The domain’s
Coursehas no interface, and should not: it is the core, not an edge.
When the requirements change
Section titled “When the requirements change”- Courses must survive a restart. Write a database adapter that
implements
CourseStoreand run the contract test on it.savethrows if the write fails, as the port’s comment says; nobody has been told yet, because the use case saves first, and the exception leaves the use case. The core does not change, but something outside it, the console ormain, must now catch the exception and report a failure, because nothing catches it today. - Email may fail, and should be retried. That is the delivery
adapter’s job: an adapter that queues the message and retries keeps
the same
Notifierport. Today, ifnotifythrows aftersave, the change is kept but the caller sees an error; an adapter that queues messages avoids that. If the registrar wants to know about a failure, the port must say how it reports one, and the use cases must decide what to do; that is a change to the core, because it is a new rule. - Two registrars work at the same time. Two use cases can each
find the same course with one free seat, each seat a different
student, and each save; the second save overwrites the first. The
copy-based port makes this lost update possible as soon as two
callers share a store. With threads, the in-memory adapter would
also need a mutex, because unsynchronised access to a
std::mapis a data race and undefined behaviour. Fixes for the lost update include a version number thatsavechecks, or a store function that runs the whole change inside one transaction; both change the port, and the concurrency pages cover them. - A web interface is added. It is another driving adapter that
calls
EnrollmentUseCases. It may need results the console never needed, such as a list of courses with free seats; that is a new use case on the driving port, implemented once in the core. - Version 0’s rules change. A new rule, such as “no more than five courses per student”, goes into the core and is tested there. Whether it needs a new driven port, here a way to count a student’s courses, is a question about what the core must ask.
Exercise
Section titled “Exercise”Exercise: Add a CLI adapter
The registrar’s office wants to run single commands from shell
scripts, such as enroll S1 CS101 and drop S1 CS101, and check the
result by its exit status: 0 when the command did what was asked,
1 when the core refused it, 2 for a command it does not understand.
The output should be one short, stable word or phrase per command,
easy for a script to match, not the console’s sentences.
- Is this a driving or a driven adapter? Which port does it use, and which CMake library does it link?
- Write its interface. How do you keep it testable without running a separate process?
- What changes in the core?
- How would you test it, and with which adapters behind the core?
- A script runs the program twice: once to enroll S1 in CS101, then again to drop S1 from CS101. With today’s adapters, what does each run see, and what must change?
Show the explained answer
- A driving adapter: it calls the core. It uses
EnrollmentUseCasesand links onlyarch_hex_driving_port, so, like the console, it cannot see the domain. - Make it a function of the port, the arguments, and two streams,
returning a status that the program’s
mainreturns asstatic_cast<int>(status). The example’s version follows the list. - Nothing. The CLI uses the same
enrollanddropthe console uses. If it needed something new, such as a machine-readable report, that would be a new use case in the core, not logic in the CLI. - With the real core and in-memory adapters, because the point is that the CLI’s words and statuses match what the core decides. The tests follow the list. A fake core, as in the console tests, would also work and would make each status easy to reach.
- Each run is a new process whose in-memory adapters start empty.
Unless the CLI program’s
mainadds courses and students, even the first run is refused (refused no-such-student). Whatever one run changes is lost when it exits, so the second run cannot see it. A one-shot CLI needs a persistent driven adapter: aCourseStoreand aStudentRegisterbacked by a file or a database, chosen in the CLI program’smain. That new adapter must pass the same contract test. The core and the CLI adapter do not change, which is the design working as intended.
The interface for answer 2:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A second driving adapter, for scripts: runs one command given as// program arguments, such as {"enroll", "S1", "CS101"}, writes one// short line to `out`, and returns the exit status. Usage errors go to// `err`. It uses the same driving port as the console.//// The numbers are written out because they are the program's exit// codes: a `main` would return static_cast<int>(status), and a shell// script would test for 0, 1, or 2.enum class ExitStatus { ok = 0, refused = 1, usage = 2 };
// std::span<const std::string> is a view of a run of strings that the// caller owns, such as a std::vector; nothing is copied, and the// strings cannot be changed through it. The two streams are borrowed// for the call, so a test can pass string streams and read them back.ExitStatus run_cli(core::EnrollmentUseCases& use_cases, std::span<const std::string> args, std::ostream& out, std::ostream& err);VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Picks the command from the arguments and hands it to a helper above// (enroll or drop), which calls the port, writes one word or phrase to// `out`, and returns ok or refused. Anything else is a usage error.ExitStatus run_cli(core::EnrollmentUseCases& use_cases, std::span<const std::string> args, std::ostream& out, std::ostream& err) { // The size is checked first, and `&&` stops at the first false, so // args[0], args[1], and args[2] are only read when all three exist. if (args.size() == 3 && args[0] == "enroll") return enroll(use_cases, args[1], args[2], out); if (args.size() == 3 && args[0] == "drop") return drop(use_cases, args[1], args[2], out); // Any other command, or the wrong number of arguments: nothing is // asked of the core, and nothing is written to `out`. err << "usage: enroll <student> <course> | drop <student> <course>\n"; return ExitStatus::usage;}Taking std::span<const std::string> rather than argc and argv
keeps it testable: a test passes a vector, and a real main would
copy argv[1] onward into one. Taking the streams as parameters lets
a test read what was written. Its tests, for answer 4:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The CLI adapter with the real core and in-memory adapters: adding a// driving adapter changed nothing in the core.//// LLD_TEST(name) defines one test; LLD_CHECK(condition) fails if the// condition is false; LLD_CHECK_EQ(actual, expected) fails, printing// both, unless they are equal. They come from lld_test.hpp.namespace {
// The whole program in miniature: real core, in-memory stores, and// three std::ostringstream objects, streams that write into a string a// test can read back with str(). `mail` catches the notifications;// `out` and `err` are the CLI's two streams. Members are built in// declaration order, so `mail` exists before the notifier borrows it.// The setup is the core tests' one: CS101 with one seat, S1 and S2.struct Office { adapters::MemoryCourses courses; adapters::MemoryStudents students; std::ostringstream mail; adapters::StreamNotifier notifier{mail}; core::EnrollmentService service{courses, students, notifier}; std::ostringstream out; std::ostringstream err;
Office() { service.add_course("CS101", 1, "Software Design"); service.add_student("S1", "Ada Lovelace"); service.add_student("S2", "Grace Hopper"); }
// A test writes office.run({"enroll", "S1", "CS101"}): the brace list // builds the vector, which then converts to the span run_cli takes. // The vector lives until run returns, so the span stays valid. adapters::ExitStatus run(std::vector<std::string> args) { return adapters::run_cli(service, args, out, err); }};
} // namespace
// S1 takes the one seat (ok), S2 is waitlisted at 1 (ok), S2 again is// refused (exit status refused), and dropping S1 promotes S2 (ok). The// last check reads everything written to `out`: one line per command.// The two string literals side by side are joined into one string.LLD_TEST(the_cli_reports_with_short_words_and_exit_statuses) { Office office; LLD_CHECK(office.run({"enroll", "S1", "CS101"}) == adapters::ExitStatus::ok); LLD_CHECK(office.run({"enroll", "S2", "CS101"}) == adapters::ExitStatus::ok); LLD_CHECK(office.run({"enroll", "S2", "CS101"}) == adapters::ExitStatus::refused); LLD_CHECK(office.run({"drop", "S1", "CS101"}) == adapters::ExitStatus::ok); LLD_CHECK_EQ(office.out.str(), std::string{"seated\nwaitlisted 1\nrefused already-waitlisted\n" "left-seat promoted S2\n"});}
// "report" is a console command but not a CLI one: usage status, nothing// on `out`, and a usage message on `err`.LLD_TEST(the_cli_rejects_unknown_commands_with_a_usage_status) { Office office; LLD_CHECK(office.run({"report", "CS101"}) == adapters::ExitStatus::usage); LLD_CHECK(office.out.str().empty()); LLD_CHECK(!office.err.str().empty());}Summary
Section titled “Summary”- Hexagonal architecture puts the rules and use cases in a core and connects it to the world through ports the core owns, with adapters outside that implement or call them.
- A driving port is how the outside asks the core to act; a driven port is how the core asks the outside for something. Every dependency points into the core.
- Shape ports by what the use cases need, in the core’s terms,
and split them by question. A port shaped like a technology moves
the
#includebut not the knowledge. - A storage port that trades in copies (find, change, save) can be
implemented by a database. It costs a copy, a
savethat must not be forgotten, and care with references into returned temporaries. - One CMake library per port makes the build refuse a driving adapter that reaches into the domain, and a test proves it.
- Test the core with in-memory adapters and a recording notifier, every storage adapter with one contract test, and driving adapters with a fake core.
- The interfaces pay for themselves when there are real rules and more than one adapter per port; otherwise they are indirection without variation.
- The clean architecture page generalises these rings and names the
dependency rule; the dependency injection and composition roots
page looks at how
mainwires larger programs.