From classes to components
What you will learn on this page
Section titled “What you will learn on this page”- What application architecture decides that the design of single classes does not.
- The difference between a module and a component, as this site uses the words.
- The running application of this section: course enrollment, with seats, waitlists, and notifications.
- How to find module candidates in a working program, by asking what changes for different reasons.
- Why a set of distributed microservices is not the default answer to a low-level design problem.
What application architecture decides
Section titled “What application architecture decides”Class design decides what one class knows and does. Application architecture decides the same things one level up, for groups of classes:
- The parts. Which groups of classes belong together, and what each group is responsible for.
- Dependency direction. Which parts may know about which. If the enrollment rules include the email code, every change to email can break enrollment.
- Where state lives. Which part owns the courses and the waitlists, and which parts only read them.
- How the parts talk. A function call in the same program, an event that someone handles later, or a message over a network.
- Where a change is committed. Which code decides that a seat and a waitlist change together, or not at all.
- Where tests can cut. Which parts can be tested without the others, and with what in their place. These are the testing seams.
- Where failures are handled. Which part notices that email is down, and what the student sees.
What these decisions share is how much code depends on them. A private member function can be renamed in a minute. A rule such as “the enrollment rules never include storage code” shapes every file written after it, and undoing it later means touching all of them. That is why architecture is decided early, but only as much as the requirements justify: each decision costs effort today and pays only if the change it prepares for actually comes.
Modules and components
Section titled “Modules and components”The two words are used in several ways in the industry, and some writers use them as synonyms. This site uses them like this:
| Term | What it is | What it has | In C++, usually |
|---|---|---|---|
| Module | A unit of source code with one responsibility and a public interface; the rest of it is hidden | A public interface, private details, and a list of what it may depend on | A namespace with its headers and sources, often its own library target in the build |
| Component | A unit that can be replaced or deployed as a whole, behind interfaces it provides and interfaces it needs | Provided and required interfaces; its own build output | A library or an executable; sometimes a separate process |
The difference is in the question each answers. A module answers “where does this code belong, and what may it use?” A component answers “what can be swapped or shipped on its own?” Most modules in a small program are never shipped on their own, so they never become components. A component usually contains one or more modules. A static library made only to enforce a module’s dependencies is still a module; it becomes a component when it is meant to be replaced or shipped separately.
The running application: course enrollment
Section titled “The running application: course enrollment”The rest of the Architecture section uses one application, so that each style can be compared on the same problem. The registrar’s office asks for this:
“Students enroll in courses with limited seats. When a course is full they should be able to wait for a seat, and we should tell them when they get one.”
After the questions from the Requirements section, the requirements used by the examples are:
| ID | Requirement |
|---|---|
| E1 | A course has a code (CS101), a title, and a capacity of at least 1 seat. |
| E2 | A student has an id (S1) and a name, and is registered before enrolling. |
| E3 | Enrolling takes a free seat if there is one; otherwise the student joins the end of the course’s waitlist. |
| E4 | A student cannot hold a seat and a waitlist place, or two of either, in the same course; the request is refused with a reason. |
| E5 | When a seated student drops, the first student on the waitlist takes the seat. A waitlisted student who drops just leaves the list. |
| E6 | Students are told when they get a seat, at once or from the waitlist, and when they join a waitlist, with their position. |
| E7 | A course report shows seats taken and capacity, the seated students in order, and the waitlist in order. |
| E8 | Unknown students and courses, and malformed commands, are refused with a reason; nothing changes. |
The assumed scale is small: about 2,000 students, 150 courses, at most 300 seats per course, one office, and one team maintaining the program. One quality constraint matters more than speed: a course’s seats and its waitlist must always change together. A student who drops must never leave a free seat while someone is still waiting.
The program is driven by a registrar’s console, one command per line:
course CS101 2 Software Designstudent S1 Ada Lovelaceenroll S1 CS101drop S1 CS101report CS101Real email would make the examples hard to run and test, so every version writes its notifications to a stream instead. Each version on the following pages runs the same script and prints the same text, and the build checks that they do. Only the structure differs.
Version 0: one class does everything
Section titled “Version 0: one class does everything”The first version is the program most people would write first, and
for a program this size it is not a bad one. One class, Registrar,
reads each command, applies the rules, keeps the data in maps, and
writes the notifications:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Version 0 of the enrollment program: one class does everything. It// reads a command, applies the rules, keeps the data, and writes the// notifications. The idea to notice is that every job lives behind one// public function, run(): there is no way to ask for "the waitlist rule"// without also going through the text parsing and the reply wording.// It never throws for a bad command; every problem becomes a "refused:"// reply string.class Registrar {public: // Notifications are written to `notifications`, which must outlive // the Registrar. The class keeps only a reference (see notifications_ // below), so it borrows the stream and never owns or closes it. // `explicit` stops a stream from turning into a Registrar by accident. explicit Registrar(std::ostream& notifications);
// Runs one command line and returns the reply, "ok: ..." or "refused: ...". // std::string_view is a cheap, read-only view of someone else's text, so // the caller's line is not copied just to be read. Any notification for // this command is written to the stream before the reply is returned. std::string run(std::string_view line);
private: // One course and everything known about it, kept together by value. // The two lists hold student ids (strings), not Student objects: a // student's name is looked up in students_ when a report needs it. struct Course { std::string title; int capacity = 1; std::vector<std::string> seated; // student ids, in enrollment order std::deque<std::string> waitlist; // student ids, first in line first }; // A std::deque is used for the waitlist because the first student leaves // from the front (pop_front) when a seat opens and new students join at // the back (push_back), and a deque does both cheaply. A std::vector // suits `seated`, where new students are only ever added at the end.
// One handler per command word. Each takes the whole command split into // words (words[0] is the command itself, words[1] the first argument) // and returns the reply text. report is `const` because it only reads. std::string add_course(const std::vector<std::string>& words); std::string add_student(const std::vector<std::string>& words); std::string enroll(const std::vector<std::string>& words); std::string drop(const std::vector<std::string>& words); std::string report(const std::vector<std::string>& words) const;
// The data lives in plain maps owned by the Registrar. A std::map keeps // its keys sorted and finds a key quickly, even when there are many. std::map<std::string, Course> courses_; // by course code std::map<std::string, std::string> students_; // student id -> name // A reference member: the stream belongs to whoever built the Registrar // (main passes std::cout, the tests pass a string stream). std::ostream& notifications_;};run turns a line into words and dispatches on the first one:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The front door: turns one line of text into a reply. It splits the line// on spaces into words, looks at the first word, and hands the whole word// list to the matching handler. Each `if` returns at once, so only one// handler runs. A blank line or an unknown first word is refused, never// thrown. "enroll S1 CS101" becomes {"enroll", "S1", "CS101"} and goes to// enroll().std::string Registrar::run(std::string_view line) { const std::vector<std::string> words = split(line); // Check before reading words[0]: indexing an empty vector is undefined. if (words.empty()) return "refused: empty command"; // A const reference is just another name for words[0]; no copy is made. const std::string& command = words[0]; if (command == "course") return add_course(words); if (command == "student") return add_student(words); if (command == "enroll") return enroll(words); if (command == "drop") return drop(words); if (command == "report") return report(words); return "refused: unknown command " + command;}The interesting function is enroll. Read the comments: it parses,
looks up, applies the rules, changes the data, and formats an email,
in one function body.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Handles "enroll <student> <course>". The result is one reply string:// "ok: ... enrolled", "ok: ... waitlisted (position 2)", or a "refused:"// reason. A refused command changes nothing, because every check comes// before the first change. Four jobs are mixed in one body, marked by the// "..." comments: reading the command, finding the data, applying the rules,// and telling the student.std::string Registrar::enroll(const std::vector<std::string>& words) { // Reading the command... // Exactly three words: the command, a student id, a course code. if (words.size() != 3) return "refused: usage: enroll <student> <course>"; const std::string& student = words[1]; const std::string& code = words[2];
// ...finding the data... if (!students_.contains(student)) return "refused: no student " + student; // find returns an iterator: either a pointer-like handle to the // (code, Course) entry, or courses_.end(), which means "not there". const auto found = courses_.find(code); if (found == courses_.end()) return "refused: no course " + code; // found->second is the Course inside the map. `Course&` is a reference // to it, not a copy, so the changes below change the stored course. Course& course = found->second;
// ...applying the rules... // A student may hold only one place per course: a seat or a waitlist // spot, not both and not twice. std::ranges::find walks the list from // the start and returns end() if the id is not in it. if (std::ranges::find(course.seated, student) != course.seated.end()) { return "refused: " + student + " is already enrolled in " + code; } if (std::ranges::find(course.waitlist, student) != course.waitlist.end()) { return "refused: " + student + " is already on the waitlist for " + code; } // A free seat? std::ssize gives the size as a signed number, so it can // be compared with the int capacity without a signed/unsigned warning. if (std::ssize(course.seated) < course.capacity) { course.seated.push_back(student); // copies the id into the course // ...and telling the student, all in one function. notifications_ << "notify " << student << ": you have a seat in " << code << ' ' << course.title << '\n'; return "ok: " + student + " enrolled in " + code; } // No seat left: join the back of the waitlist. The position is the new // length of the waitlist, so the first student to wait is number 1. course.waitlist.push_back(student); const std::string position = std::to_string(course.waitlist.size()); notifications_ << "notify " << student << ": you are number " << position << " on the waitlist for " << code << ' ' << course.title << '\n'; return "ok: " + student + " waitlisted for " + code + " (position " + position + ")";}How this code works: One enroll command through version 0
Follow the line enroll S3 CS101 from the script. Every step happens
inside the one Registrar object, which owns all the data.
maincallsregistrar.run(line). The line is passed as astd::string_view, sorunreads the script’s text without copying it.runsplits and dispatches.splitturns the line into the words{"enroll", "S3", "CS101"}. The first word is"enroll", soruncallsenroll(words)and returns whateverenrollreturns.enrollreads the command. There are exactly three words, so the usage check passes, andstudentandcodebecome names forwords[1]andwords[2].enrollfinds the data. S3 is instudents_, andcourses_.find("CS101")finds the course.courseis a reference to theCoursestored in the map, so changing it changes the stored data.enrollapplies the rules. S3 is not already seated or waiting. The course holds two seats, and S1 and S2 already have them, sostd::ssize(course.seated) < course.capacityis2 < 2, which is false.enrollchanges the data and tells the student. S3 is pushed onto the back of the waitlist, which now has one entry, so the position is"1". The notification goes to the stream given to the constructor, then the reply string goes back throughruntomain, which prints it. That is why thenotifyline appears before theok:line in the output.
The same function, for the first six enroll commands of the script (capacity 2):
| Command | Seated before | Waiting before | Result |
|---|---|---|---|
enroll S1 CS101 |
none | none | seated; reply ok: S1 enrolled in CS101 |
enroll S2 CS101 |
S1 | none | seated (1 is less than 2) |
enroll S3 CS101 |
S1, S2 | none | waitlisted, position 1 (2 is not less than 2) |
enroll S4 CS101 |
S1, S2 | S3 | waitlisted, position 2 |
enroll S3 CS101 |
S1, S2 | S3, S4 | refused: already on the waitlist |
enroll S9 CS101 |
S1, S2 | S3, S4 | refused: no student S9 |
The two refusals return before anything changes, so the course is the same after them as before. Notice that the parsing (step 3), the lookup (step 4), the rule (step 5), and the email text (step 6) are all in one function body. Those are the seams the next pages pull apart.
The program runs a fixed script. Notification lines start with
notify, replies with ok: or refused::
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
int main() { // The layered version runs the same script and must print the same text. // A fixed array of commands, built into the program. Each entry is a // std::string_view pointing at a string literal, which lives for the whole // run, so nothing is copied or freed. constexpr: it is known 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 Registrar borrows std::cout for its notifications, so notification // lines and replies end up interleaved in one output, in the order they // happen. std::cout outlives the Registrar, as the constructor requires. Registrar registrar{std::cout}; // A string_view is small, so each line is taken by value (a cheap copy). for (const std::string_view line : script) { std::cout << "> " << line << '\n'; const std::string reply = registrar.run(line); // may print notifications first std::cout << reply << '\n'; }}> 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)Two lines are worth checking against the requirements. After
drop S1 CS101, S3, first on the waitlist, gets the seat and a
notification (E5, E6). After drop S4 CS101, S4 just leaves the
waitlist and nobody is told anything: E6 asks for no message when
positions move, and here nobody was behind S4.
What version 0 does well, and where it strains
Section titled “What version 0 does well, and where it strains”It is short, and everything about a command is in one place. Every rule is checked, by these tests or by the recorded output, but only through text:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Version 0 can only be tested through its text commands: the rules,// the data, and the notifications are all behind run().namespace {
// A test fixture: a fresh registrar with one course of capacity 1 (CS101)// and two students (S1, S2), so each test starts from the same state.// std::ostringstream is an output stream that writes into a string, so a// test can read the "sent" notifications back with mail.str().struct Office { // Members are built in the order they are declared: `mail` exists // before `registrar` is given a reference to it, and is destroyed // after it. Swapping these two lines would hand over a stream that // does not exist yet. std::ostringstream mail; Registrar registrar{mail};
// The setup commands' replies are ignored: run is not [[nodiscard]], // and the tests below check the replies that matter. Office() { registrar.run("course CS101 1 Software Design"); registrar.run("student S1 Ada Lovelace"); registrar.run("student S2 Grace Hopper"); }};
} // namespace
// LLD_TEST(name) defines one test, and LLD_CHECK_EQ(actual, expected)// records a failure if the two are not equal (==), printing both. They// come from the site's small test header, lld_test.hpp. Wrapping the// expected text in std::string{...} gives both sides the same type, so the// check compares two std::string values.//// Sets up a course with one seat; S1 takes it and S2 must wait. Proves the// two replies and that exactly two notifications were written, in order.LLD_TEST(a_full_course_puts_the_next_student_on_the_waitlist) { Office office; LLD_CHECK_EQ(office.registrar.run("enroll S1 CS101"), std::string{"ok: S1 enrolled in CS101"}); LLD_CHECK_EQ(office.registrar.run("enroll S2 CS101"), std::string{"ok: S2 waitlisted for CS101 (position 1)"}); LLD_CHECK_EQ(office.mail.str(), std::string{"notify S1: you have a seat in CS101 Software Design\n" "notify S2: you are number 1 on the waitlist for CS101 " "Software Design\n"});}
// S1 is seated and S2 waits; S1 drops. Proves that S2 is moved into the// freed seat and that the waitlist is then empty, read through "report".LLD_TEST(dropping_a_seat_moves_the_first_waiting_student_in) { Office office; office.registrar.run("enroll S1 CS101"); office.registrar.run("enroll S2 CS101"); LLD_CHECK_EQ(office.registrar.run("drop S1 CS101"), std::string{"ok: S1 dropped CS101; S2 moved from the waitlist"}); LLD_CHECK_EQ(office.registrar.run("report CS101"), std::string{"ok: CS101 Software Design, 1/1 seats taken\n" " seated: S2 Grace Hopper\n" " waitlist: (none)"});}
// S1 is seated, then seven bad commands are tried: a duplicate enrollment,// an unknown student, dropping a student who holds no place, a capacity of// 0, a capacity that is not a whole number ("2x"), a missing argument,// and an unknown command. Each gets a "refused:" reply, and the// final report proves CS101 is exactly as it was.LLD_TEST(refused_commands_change_nothing) { Office office; office.registrar.run("enroll S1 CS101"); LLD_CHECK_EQ(office.registrar.run("enroll S1 CS101"), std::string{"refused: S1 is already enrolled in CS101"}); LLD_CHECK_EQ(office.registrar.run("enroll S9 CS101"), std::string{"refused: no student S9"}); LLD_CHECK_EQ(office.registrar.run("drop S2 CS101"), std::string{"refused: S2 is not enrolled in or waiting for CS101"}); LLD_CHECK_EQ(office.registrar.run("course CS102 0 Empty"), std::string{"refused: capacity must be a whole number of at least 1"}); LLD_CHECK_EQ(office.registrar.run("course CS102 2x Typo"), std::string{"refused: capacity must be a whole number of at least 1"}); LLD_CHECK_EQ(office.registrar.run("enroll S1"), std::string{"refused: usage: enroll <student> <course>"}); LLD_CHECK_EQ(office.registrar.run("register S1"), std::string{"refused: unknown command register"}); LLD_CHECK_EQ(office.registrar.run("report CS101"), std::string{"ok: CS101 Software Design, 1/1 seats taken\n" " seated: S1 Ada Lovelace\n" " waitlist: (none)"});}The strain shows when you ask what one change would touch:
- To test the waitlist rule, a test must write a command, parse a reply, and read the email text. A change to the reply wording breaks rule tests that have nothing to do with wording.
- To keep the data after a restart, the maps must be replaced by a database, inside the class that also parses commands and formats email.
- To replace the console with a web form, the parsing must be separated from the rules it is mixed with in every function.
- To send real email, which can fail or be slow, the code that changes the seats must decide what to do when the email does not go out.
None of these is a reason to restructure version 0 today. Each is a reason when the change is actually requested. The point of this page is to see where the seams would go.
Finding module candidates
Section titled “Finding module candidates”A module candidate is a group of code that changes for its own reasons, at the request of its own people. That is the Single Responsibility Principle applied to groups of classes instead of one class. To find candidates, list each concern in the program, where it lives, and who would ask for it to change:
| Concern | Where it is in version 0 | Who asks for a change | Likely change |
|---|---|---|---|
| Reading commands, writing replies | split, the checks at the top of each function, the reply strings |
Office staff, user interface work | A web form instead of the console |
| Enrollment rules | The capacity, duplicate, and waitlist checks in enroll and drop |
The registrar | New rules: prerequisites, priority |
| Keeping the data | The courses_ and students_ maps |
IT | A database; survive restarts |
| Telling students | The notifications_ << lines |
Office staff, IT | Email and SMS, sent without delay |
| Running one request | The order of steps in each function | Whoever adds a feature | Changes with each new use case |
That gives four clear candidates and one that appears only when the others are separated. Running one request, the last row, is the code that finds the data, asks the rules, and tells the students. It becomes its own part, the application part, once there is something to coordinate.
Notice what is not a candidate: “students” and “courses”. Splitting
by nouns gives a StudentModule and a CourseModule, but the
enrollment rules need both, so most rule changes touch both. Group
by reason to change, not by noun.
The candidates, and which may depend on which:
Text description of the diagram
A component diagram of five module candidates. The Console calls the Enrollment use cases. The use cases ask the Enrollment rules, read and save through Storage, and send through Notifications. Storage stores the rule objects, so it depends on the rules. The Enrollment rules have no outgoing arrows: they depend on nothing. Nothing depends on the Console.
Diagram source (Mermaid)
flowchart TB
Console["Console<br/>reads commands, writes replies"]
App["Enrollment use cases<br/>runs one request"]
Rules["Enrollment rules<br/>Course: seats, waitlist"]
Store["Storage<br/>courses and students"]
Mail["Notifications<br/>tells students"]
Console -->|calls| App
App -->|asks| Rules
App -->|reads and saves through| Store
App -->|sends through| Mail
Store -->|stores| RulesThe arrows are dependencies: “this part’s code mentions that part”. The most important property of the diagram is the box with no outgoing arrows. The rules depend on nothing, so they can be tested alone and kept when the console, the storage, or the email changes. This is the direction the Dependency Inversion Principle asks for: policy should not depend on details. Here only part of it is in place. Storage depends on the rules, but the use cases still depend on the concrete storage and notifications. Interfaces owned by the use cases, on the hexagonal architecture page, finish the job.
One request at run time
Section titled “One request at run time”The same candidates, now showing what happens at run time for
drop S1 CS101 when S3 is waiting. Control goes down and back; data
comes back as results:
Text description of the diagram
A sequence diagram for one drop command. The Console asks the Enrollment use cases to drop S1 from CS101. The use cases ask Storage for course CS101 and get it back. They ask the Course to drop S1; the Course answers that S1 left a seat and S3 was promoted. The use cases save the course through Storage, then ask Notifications to tell S3 that a seat opened, then return “dropped, S3 promoted” to the Console, which formats the reply text.
Diagram source (Mermaid)
sequenceDiagram
participant C as Console
participant A as Enrollment use cases
participant S as Storage
participant R as Course (rules)
participant M as Notifications
C->>A: drop S1 from CS101
A->>S: find course CS101
S-->>A: the course
A->>R: drop S1
R-->>A: left a seat, S3 promoted
A->>S: save CS101
A->>M: tell S3 a seat opened
A-->>C: dropped, S3 promoted
Note over C: formats the reply textTwo things are visible here that the dependency diagram hides. The rules decide before anyone is told: the email is sent only after the course has changed. And the failure path has a question in it: if telling S3 fails, should the drop stand? Version 0 never asks: it ignores whether the write to the stream succeeded. With real email it must be answered, and the page on transaction and persistence boundaries answers it.
Why not microservices?
Section titled “Why not microservices?”A common answer to “design a course-enrollment system” is a set of services: an enrollment service, a waitlist service, a notification service, each with its own database, talking over the network. For a low-level design problem, and for this application, that is almost always the wrong starting point. Each boundary between processes turns a function call into a network call, and that brings costs a function call does not have:
- Partial failure. A function call either returns or throws. A network call can time out with no way to know whether the other side did the work. Every call needs a timeout, a retry rule, and a way to make retries safe.
- Consistency across stores. Seats and the waitlist must change together. In one process with one store, that is one transaction. In two services with two databases, it needs a protocol: two-phase commit, which blocks if the coordinator fails, or a saga with compensating steps, which accepts a period in which the two disagree.
- Latency. Each hop adds network time and serialization to every request.
- Operations. Each service needs deployment, monitoring, logging, versioned interfaces, and someone on call.
- Testing. A test of one enrollment must start, or fake, several services.
Those costs buy real things: teams that release independently, parts that scale separately, and faults that stay in one process. Those are organizational and operational needs. Here there is one team, one office, 2,000 students, and a strong consistency need, so none of them applies.
When version 0 is enough
Section titled “When version 0 is enough”Keep the single class while all of these hold:
- One person or a small team reads all of it.
- The data does not need to survive a restart, or a file written at exit is enough.
- There is one way in, such as the console, and no plan for another.
- The tests through text commands are fast and easy to read.
A teaching tool used for one afternoon, or a prototype to find out what the registrar really wants, is better as version 0 than as four layers.
Common mistakes
Section titled “Common mistakes”- Drawing boxes before reading the requirements. Architecture answers questions such as “must the data survive a restart?” and “will there be a web form?” Boxes drawn without those answers are guesses.
- Splitting by nouns. A
StudentModuleand aCourseModuleboth change for every enrollment rule. Split by reason to change. - One module per class. A module with one small class has an interface as large as its contents and hides nothing.
- Mixing dependency and run-time arrows in one diagram. Draw “who knows whom” and “what happens when” separately.
- Starting with services. Network boundaries cost on every request and are hard to move. Start with modules in one program; split only for a requirement that needs it.
When the requirements change
Section titled “When the requirements change”- Data must survive a restart: the storage candidate becomes a real module with an interface the use cases call, and the question of who commits a change appears. Repository and Unit of Work answer it.
- A web form is added: a second presentation part calls the same use cases. If the rules were mixed into the console, they would be copied into the web code.
- Email must not slow enrollment: notifications are sent after the change is saved, perhaps by a separate worker. That is the first requirement in this application that could justify a separate process, and the event-driven components page covers it.
- Each department adds its own rules: the rules module needs extension points, and the modular monolith and plugin architecture pages apply.
The rest of this section
Section titled “The rest of this section”The next page, Layered architecture, turns
the candidates into four layers and runs the same script.
Modular monolith splits it by
feature instead, and
Hexagonal architecture puts the rules in a
core behind ports it owns, and
Clean architecture concepts
names the rule they share and splits the core into use cases.
Dependency injection and composition
roots shows how main builds and
owns the object graph. DDD building
blocks draws aggregate boundaries
from the rules, and Repository and Unit of
Work puts them behind
storage. DTOs, domain objects, and persistence
records gives each boundary
its own data shape, and API contracts and validation
placement decides where
each check on incoming data belongs. Transaction and persistence
boundaries decides which
changes are kept together, and who commits them. MVC, MVP, and
MVVM separates a user interface from the
model it shows, and Event-driven application
components lets components react to
each other’s events. Plugin architecture
lets other people add features through a versioned interface.
Choosing an architecture from
requirements closes the section: it maps
each requirement signal to the choice it justifies, and shows how to
record each decision.
Exercise: Find the module candidates
A library’s loan desk uses one class, LoanDesk. Its run function
reads commands such as lend B12 M7 and return B12. It checks that
member M7 has fewer than five books and no unpaid fines, records the
loan in a std::map, prints a receipt, and every night writes a list
of overdue books to a file that a printer picks up. The library plans
a self-service kiosk next year and wants fines to be calculated by a
new rule from the finance office.
- List the module candidates, and for each, who would ask for it to change.
- Draw, in words, which candidates may depend on which. Which one should depend on nothing?
- Which planned change touches which candidates?
- The library has one branch and one developer. Someone proposes a loan service, a member service, and a fines service. Give two reasons against it, from this description.
Show the explained answer
- Candidates. Commands and receipts: the desk staff and the kiosk project. Loan rules (the five-book limit, no lending with unpaid fines, and fines once finance’s rule arrives): the library’s policy, and the finance office for fines. Keeping loans and members: IT. The nightly overdue list: the staff who use it, and whoever runs the printer. Coordinating one request: whoever adds a feature. “Books” and “members” are nouns, not candidates.
- Dependencies. Commands call the use cases. The use cases ask the loan rules, read and save through storage, and produce the overdue list through the report writer. Storage stores the rule objects. The loan rules depend on nothing: they are the policy both the desk and the kiosk must share.
- Changes. The kiosk adds a second presentation part that calls the same use cases; the rules do not change. The new fine rule changes mainly the loan rules, plus storage if the rule needs data not kept today, such as payments, and the receipt if fines are printed on it.
- Against three services, any two of: a loan needs the member’s fines and loan count at the moment of lending, so it would cross two services, and a network failure could lend a book to a member who owes money; one developer must then deploy and monitor three services; nothing in the description needs independent scaling or release. Separate modules in one program give the same separation of code without those costs.
Summary
Section titled “Summary”- Application architecture decides the parts of a program, which way their dependencies point, where state and transactions live, how the parts talk, and where tests and failures are handled. It is decided early, but only as far as the requirements justify.
- A module is a unit of source code with a public interface; a component is a unit that can be replaced or deployed on its own.
- The course-enrollment application, with seats, waitlists, and notifications, runs through this section; every version prints the same output.
- Find module candidates by asking what changes for different reasons, and who asks. Do not split by nouns.
- The rules should depend on nothing. Storage and the user interface depend on the rules or the use cases; for now the use cases depend directly on storage and notifications, which later pages remove.
- Distributed microservices add partial failure, cross-store consistency, latency, and operations cost. Start with modules in one program, and split only for a requirement that needs it.