Separation of concerns
What you will learn on this page
Section titled “What you will learn on this page”- What a concern is, and the four concerns that appear in almost every program: getting the input, applying the rules, shaping the output, and deciding the order of the steps.
- The highlighter test: how to find the concerns inside an existing function, line by line.
- Why the parts should pass values to each other instead of streams,
files, or
std::cout. - Why splitting code into steps is not the same as separating concerns.
- How the separation pays off when a second output format is needed, and when it is not worth doing.
The problem
Section titled “The problem”A payroll team wants a weekly overtime report from a timesheet file. Each line of the file is one day’s work for one person.
person,week,workedAna,1,10:00Ana,1,12:30Ben,1,7:45The requirements:
- FR-1 Read the timesheet: a header line, then
person,week,hours:minuteson each line. - FR-2 For each person and week, add up the time worked. Time above 40 hours in one week is overtime.
- FR-3 Print a text report, ordered by person, then by week, with the time worked and the overtime.
- FR-4 A bad line must not stop the report. List the numbers of the lines that were skipped.
A first version does all of this in one function of about 35 lines. It
works, and it prints the right report. Then two things happen. The payroll
system asks for the same numbers as CSV, and a tester asks how to check
the 40-hour rule without writing a file and reading std::cout. Both
questions are hard to answer, for the same reason: four different jobs are
woven into the same lines.
What a concern is
Section titled “What a concern is”A concern is one kind of question that code has to answer, or, looking at it from the other side, one reason the code might have to change. Separation of concerns means giving each concern its own place, so that a change to one concern touches only that place.
Most programs that take data in and produce a result have the same four concerns:
| Concern | The question it answers | Who asks for changes | In the overtime report |
|---|---|---|---|
| Input | Where does the data come from, and in what format? | whoever owns the data | read the lines, split at commas, read hours:minutes |
| Domain rules | What does the data mean? What do we calculate? | the business (payroll) | add up a person’s week; time above 40 hours is overtime |
| Output format | How should the results look? | the readers of the report | text columns, 9:30 style times, or CSV |
| Orchestration | In what order do the steps run, and where does output go? | whoever runs the program | read, then calculate, then format, then write to a stream |
There are often others: error handling policy, logging (see Observability), configuration, storage, and talking to other systems. The four above are enough to start with, and they are the ones that are tangled most often.
The domain rule is usually the most valuable concern and the one that should be easiest to test, because it is what the program is for. Input and output are where the outside world is, so they change for outside reasons: a new file format, a new reader of the report.
The highlighter test
Section titled “The highlighter test”To find the concerns in existing code, go through it line by line and mark each line with the concern it serves, as if with four highlighter pens. If one function needs more than one colour, it has more than one concern. If the colours are interleaved, so that one line of rule sits between two lines of formatting, the concerns are tangled.
Here is the first version of the report:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Before: one function reads, parses, applies the overtime rule, formats,// and prints. Each concern is a few lines, all tangled together.namespace before {
// Reads lines like "Ana,1,9:30" (person, week, hours:minutes worked that// day) after one header line, adds up the time per person per week, and// prints each week's total and overtime (time above 40 hours) to// std::cout. Lines it cannot read are listed by number at the end. For// well-formed lines its output is right, and the new design must match// it; the trouble is that all four concerns are mixed in one body, so none// can be changed or tested alone. `inline` lets the body sit in a header.inline void overtime_report(std::istream& in) { // A std::map keeps its keys sorted. The key is a pair (person, week), // so the report comes out ordered by person, then by week. The value // is the minutes worked that week. std::map<std::pair<std::string, int>, int> minutes; // (person, week) -> minutes std::string line; std::string skipped; // the bad line numbers, already as text: "9, 10" int number = 0; // the number of the line just read; the header is 1 std::getline(in, line); // header ++number; // getline reads one line into `line` and is false at the end of input. while (std::getline(in, line)) { ++number; // Find the two commas and the colon. find returns the position, or // std::string::npos ("not found"). Each search starts one place // after the previous mark. const auto c1 = line.find(','); const auto c2 = line.find(',', c1 + 1); const auto colon = line.find(':', c2 + 1); int week = 0, h = 0, m = 0; // A pointer to the first character, so `s + i` is the address of // character i. from_chars works on a [first, last) pointer range. const char* s = line.data(); // Skip the line if a mark is missing, or if a number does not fill // its whole field. std::from_chars reads an int from the range and // returns `ptr`, where it stopped; ptr equal to the field's end // means every character was used. `||` stops at the first true // test, so from_chars only runs once all three marks were found. // Flaws hide here: the error code is never checked, and for an // empty field ptr is already at the end, so "Ben,,8:00" is read as // week 0. A leading '-' is accepted, so "-1:30" adds -30 minutes, // and ",1,9:30" is kept with an empty name. if (c1 == std::string::npos || c2 == std::string::npos || colon == std::string::npos || std::from_chars(s + c1 + 1, s + c2, week).ptr != s + c2 || std::from_chars(s + c2 + 1, s + colon, h).ptr != s + colon || std::from_chars(s + colon + 1, s + line.size(), m).ptr != s + line.size() || m > 59) { // Output format, mixed into input: ", " goes before every // number except the first. skipped += (skipped.empty() ? "" : ", ") + std::to_string(number); continue; // on to the next line } // The domain rule's first half, inside the reading loop: add this // day's minutes to the (person, week) total. operator[] creates // the entry with 0 the first time a key is seen. minutes[{line.substr(0, c1), week}] += h * 60 + m; } // Orchestration: the output always goes to std::cout. std::cout << "Overtime report\n"; // Each map element is a (key, value) pair; the structured binding names // them `key` (person, week) and `worked` (minutes). for (const auto& [key, worked] : minutes) { // The domain rule's second half, inside the printing loop: time // above 40 hours (2400 minutes) is overtime, otherwise none. const int overtime = worked > 40 * 60 ? worked - 40 * 60 : 0; // Output format: the name left-aligned in 6 columns, the hours // right-aligned in 2, and minutes as two digits. worked / 60 is // whole hours and worked % 60 the minutes left over (2550 gives // 42 and 30). setw applies to the next value only; setfill('0') // pads minutes like 5 to "05" and must be set back to ' ' after. std::cout << std::left << std::setw(6) << key.first << " week " << key.second << " worked " << std::right << std::setw(2) << worked / 60 << ':' << std::setfill('0') << std::setw(2) << worked % 60 << std::setfill(' ') << " overtime " << overtime / 60 << ':' << std::setfill('0') << std::setw(2) << overtime % 60 << std::setfill(' ') << '\n'; } if (!skipped.empty()) std::cout << "Skipped lines: " << skipped << '\n';}
} // namespace beforeThe highlighter result:
Lines of overtime_report |
Concern |
|---|---|
getline, the header skip, the line counter |
input |
the comma and colon search, the three from_chars calls |
input |
building the skipped text "9, 10" |
output format |
minutes[{person, week}] += h * 60 + m |
domain rule |
worked > 40 * 60 ? worked - 40 * 60 : 0 |
domain rule |
std::setw, std::setfill, " worked ", " overtime " |
output format |
writing to std::cout |
orchestration |
| the order of everything above | orchestration |
All four colours, and they alternate. The domain rule is two lines, and
both are buried: one inside the reading loop, and one in the printing loop,
just above a long << chain.
Notice also that the skipped lines are collected as text while the
file is being read. The input code has already decided how the report will
look.
Bad, good, great: where do the four jobs live?
Section titled “Bad, good, great: where do the four jobs live?”The new design
Section titled “The new design”The data that flows between the parts is a few plain records. They have
no invariants to protect, so they are structs with public members (see
encapsulation, “when not to”):
struct Entry
one line of the timesheet
Data members
std::string person;int week = 0;int minutes = 0;worked that day
struct SkippedLine
a line that could not be read, and why
Data members
int line_number = 0;std::string reason;
struct Timesheet
everything input produces
Data members
std::vector<Entry> entries;std::vector<SkippedLine> skipped;
struct WeekTotal
what the rule produces
Data members
std::string person;int week = 0;int worked_minutes = 0;int overtime_minutes = 0;
enum class Format
chosen by whoever runs the report
Values
textcsv
Look at what is not in these records. SkippedLine stores a number
and a reason, not the text "9, 10": input reports what happened, and the
format decides how to show it. WeekTotal stores minutes as int, not
"42:30": the rule produces numbers, and the format turns them into text.
That is the separation showing up in the data members.
Each concern gets its own header, with the functions it offers:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Input: turning text into entries. Knows the file format; knows nothing// about overtime or about how the report looks.//// These are plain structs: values with public fields and no rules to// protect, passed from one step to the next. The `= 0` gives each number// a starting value.
// One line of the file, read: who, which week, how long that day.struct Entry { std::string person; int week = 0; int minutes = 0; // worked that day};
// A line that could not be read: its number in the file (the header is// line 1) and why. Kept as data, not text, so each format decides how to// show it.struct SkippedLine { int line_number = 0; std::string reason;};
// Everything read from one file: the good entries and the bad lines.struct Timesheet { std::vector<Entry> entries; std::vector<SkippedLine> skipped;};
// "Ana,1,9:30" -> Entry{"Ana", 1, 570}, since 9 * 60 + 30 = 570. Empty// (std::nullopt) if the line is not in that form; `reason` then says why.// `reason` is an out-parameter: a string the caller owns, which this// function fills in on failure and leaves alone on success. std::string_view// lets the caller pass any text without a copy.[[nodiscard]] std::optional<Entry> parse_entry(std::string_view line, std::string& reason);
// Reads a header line, then one entry per line. Never throws for bad lines;// they are collected in `skipped`.[[nodiscard]] Timesheet read_timesheet(std::istream& in);VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The rule: what counts as overtime. No input, no output, no text.// 40 hours as minutes. `inline constexpr`: a compile-time constant that// can be defined in a header shared by many files.inline constexpr int regular_minutes_per_week = 40 * 60;
// One person's week, worked out: total time and the overtime part of it.struct WeekTotal { std::string person; int week = 0; int worked_minutes = 0; int overtime_minutes = 0;};
// One total per person and week, ordered by person, then week.// std::span<const Entry> is a read-only view of entries stored in a row// somewhere else (a std::vector converts to it), so nothing is copied and// the function does not care which container holds them.[[nodiscard]] std::vector<WeekTotal> weekly_totals(std::span<const Entry> entries);VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Output formats: how results look. They compute nothing. Each returns// the whole report as a string instead of writing it to a stream, so a// test can compare it directly and the caller decides where it goes.[[nodiscard]] std::string format_text(std::span<const WeekTotal> totals, std::span<const SkippedLine> skipped);[[nodiscard]] std::string format_csv(std::span<const WeekTotal> totals);VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Orchestration: the order of the steps, and where input comes from and// output goes to. No rules and no formatting of its own.enum class Format { text, csv };// Reads from `in`, writes the report to `out`. Taking both streams as// parameters (instead of opening a file or using std::cout) lets main pass// std::cout and a test pass a string stream.void run_overtime_report(std::istream& in, std::ostream& out, Format format);Text description of the diagram
Four groups. Input (timesheet.hpp) holds read_timesheet and parse_entry; the rule (overtime.hpp) holds weekly_totals; formats (report.hpp) hold format_text and format_csv; orchestration (report.hpp) holds run_overtime_report. All arrows are dashed “uses” arrows. read_timesheet reads from an input stream chosen by the caller. run_overtime_report calls, in order: (1) read_timesheet, which takes text and returns a Timesheet; (2) weekly_totals, which takes entries and returns totals; (3) format_text or, for CSV, format_csv, which take totals and return a string; and (4) writes the string to an output stream chosen by the caller. The orchestrator is the only code that calls across groups, and no part owns another.
Diagram source (Mermaid)
flowchart LR
subgraph Input["timesheet.hpp: input"]
RT["read_timesheet<br/>parse_entry"]
end
subgraph Rule["overtime.hpp: the rule"]
WT["weekly_totals"]
end
subgraph Formats["report.hpp: formats"]
FT["format_text"]
FC["format_csv"]
end
subgraph Orchestration["report.hpp: orchestration"]
RUN["run_overtime_report"]
end
IN[/"std::istream<br/>chosen by the caller"/]
OUT[/"std::ostream<br/>chosen by the caller"/]
RT -.->|reads| IN
RUN -.->|"1. text in, Timesheet out"| RT
RUN -.->|"2. entries in, totals out"| WT
RUN -.->|"3. totals in, string out"| FT
RUN -.->|"3. or, for CSV"| FC
RUN -.->|"4. writes the string"| OUTThe headers depend on each other in one direction only:
| Header | Includes | Why |
|---|---|---|
timesheet.hpp |
only standard headers | input needs nothing from the rest of the program |
overtime.hpp |
timesheet.hpp |
the rule reads Entry |
report.hpp |
overtime.hpp, timesheet.hpp |
formats read WeekTotal and SkippedLine |
The rule does not include report.hpp, so it cannot know how it will be
shown. That is easy to check by reading the #include lines, and it is
worth keeping true.
The implementation, one concern at a time
Section titled “The implementation, one concern at a time”Input. parse_entry handles one line and says why it failed;
read_timesheet handles the file and collects the failures:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Splits one line at its two commas and its colon, checks each field, and// either returns the Entry or sets `reason` and returns std::nullopt. Each// check that fails leaves at once (an early return), so the code below a// check runs only for lines that passed it.std::optional<Entry> parse_entry(std::string_view line, std::string& reason) { // Find the marks. find returns a position, or npos for "not found". // If one mark is missing, the next search is skipped (`?:` passes the // npos along), so a missing comma means colon is npos too, and only // colon needs checking below. const auto c1 = line.find(','); const auto c2 = c1 == std::string_view::npos ? c1 : line.find(',', c1 + 1); const auto colon = c2 == std::string_view::npos ? c2 : line.find(':', c2 + 1); if (colon == std::string_view::npos) { reason = "expected person,week,hours:minutes"; return std::nullopt; } // A comma at position 0 means nothing came before it: no name. if (c1 == 0) { reason = "person is missing"; return std::nullopt; } // Digits only: from_chars would also accept a leading '-'. // read_int is a small helper (a lambda; [] means it uses nothing from // around it). It is true only if `text` is a whole non-negative number: // not empty, no '-', and from_chars both succeeded (ec, the error code, // equals std::errc{}, "no error") and used every character (ptr, where // it stopped, is the end). "8x", "" and "-1" are all refused. On // success the number is written into `value`, which is a reference. const auto read_int = [](std::string_view text, int& value) { if (text.empty() || text.front() == '-') return false; const char* end = text.data() + text.size(); const auto [ptr, ec] = std::from_chars(text.data(), end, value); return ec == std::errc{} && ptr == end; }; // The name is everything before the first comma. substr on a // string_view gives another view; std::string(...) copies it, so the // Entry owns its name after `line` is gone. Entry entry{std::string(line.substr(0, c1)), 0, 0}; int hours = 0; int minutes = 0; // substr(start, length). The week is between the commas: it starts just // after c1 and is c2 - c1 - 1 characters long. For "Ana,1,9:30", c1 is // 3, c2 is 5, and colon is 7, so the week is substr(4, 1), "1". if (!read_int(line.substr(c1 + 1, c2 - c1 - 1), entry.week)) { reason = "week is not a number"; return std::nullopt; } // Hours sit between c2 and the colon (substr(6, 1), "9"); minutes are // everything after the colon (substr(8), "30"), and must be 0 to 59. if (!read_int(line.substr(c2 + 1, colon - c2 - 1), hours) || !read_int(line.substr(colon + 1), minutes) || minutes > 59) { reason = "time is not hours:minutes"; return std::nullopt; } entry.minutes = hours * 60 + minutes; // 9 * 60 + 30 = 570 return entry; // an Entry converts to an optional that holds it}
// The file-level half of input: skip the header, try every other line, and// sort the results into good entries and skipped lines.Timesheet read_timesheet(std::istream& in) { Timesheet sheet; std::string line; int number = 1; // the header is line 1, so the first entry is line 2 std::getline(in, line); // header while (std::getline(in, line)) { ++number; std::string reason; // fresh for each line; filled in only on failure // `if` with a declaration: entry is the optional parse_entry returned, // and the test is true when it holds an Entry. if (auto entry = parse_entry(line, reason)) { // *entry is the Entry inside; std::move hands its name string to // the vector instead of copying it. sheet.entries.push_back(std::move(*entry)); } else { // {number, reason} builds a SkippedLine; the reason is moved too. sheet.skipped.push_back({number, std::move(reason)}); } } return sheet;}How this code works: parse_entry and read_timesheet
parse_entry does three things, in order, and leaves with a reason as
soon as one fails.
- Find the marks.
c1andc2are the positions of the two commas, andcolonthe position of the colon after them. If any is missing, the later searches are skipped andcolonends up asnpos, so one test covers all three. - Check the name.
c1 == 0means the line starts with a comma. - Read the three numbers with
read_int, which accepts only a field made entirely of digits. The fields are cut out withsubstr(start, length): the week is thec2 - c1 - 1characters after the first comma, the hours thecolon - c2 - 1characters after the second, and the minutes everything after the colon. Minutes above 59 are refused.
Here are the positions and results for some real lines (positions count from 0):
| Line | c1 |
c2 |
colon |
Fields (week, hours, minutes) | Result |
|---|---|---|---|---|---|
Ana,1,9:30 |
3 | 5 | 7 | 1, 9, 30 |
Entry{"Ana", 1, 570} |
Cy,1,9:6O |
2 | 4 | 6 | 1, 9, 6O |
time is not hours:minutes (O is a letter) |
Ben,one,8:00 |
3 | 7 | 9 | one, 8, 00 |
week is not a number |
Ana,1 |
3 | none | none | not reached | expected person,week,hours:minutes |
,1,9:30 |
0 | 2 | 4 | not reached | person is missing |
For Cy,1,9:6O, std::from_chars reads the 6 and stops at the O, so
ptr is not the end of the field and read_int says no. That is the check
the old function had too. What it lacked was the test of ec and the test
for an empty field or a leading -.
read_timesheet wraps this for a whole stream. It reads the header and
throws it away, then counts lines from 2. Each line goes to parse_entry
with a fresh reason. A good line’s Entry is moved into
sheet.entries, and a bad line becomes a SkippedLine with its number and
reason. With the example program’s input, lines 9 and 10 are skipped (the
two bad lines in the table) and the other seven lines become entries.
Notice what read_timesheet does not do: it does not add up any
minutes, and it does not write "9, 10". Those belong to the rule and to
the format.
The rule. Eight lines, with no formatting and no stream:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Two steps: add up each person's minutes per week, then work out overtime// for each week. The map does the grouping and the sorting.std::vector<WeekTotal> weekly_totals(std::span<const Entry> entries) { // A std::map keeps its keys sorted; a pair sorts by its first part, // then its second. worked[key] creates a 0 the first time a key is // seen, so `+=` both starts and grows each total. std::map<std::pair<std::string, int>, int> worked; // ordered by person, then week for (const Entry& e : entries) worked[{e.person, e.week}] += e.minutes;
// key.first is the person, key.second the week. Overtime is the time // above 40 hours, or 0 if there is none (`?:` picks one of the two). std::vector<WeekTotal> totals; for (const auto& [key, minutes] : worked) { const int overtime = minutes > regular_minutes_per_week ? minutes - regular_minutes_per_week : 0; totals.push_back({key.first, key.second, minutes, overtime}); } return totals;}The formats. Each one only arranges values it is given:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The text layout: a title, one line per week, then the skipped line// numbers if there are any. Two small helpers defined above (not shown):// padded(text, 6) adds spaces on the right up to 6 characters, and// clock(minutes, width) turns minutes into hours:minutes, padding the// hours on the left to `width` characters: clock(480, 2) is " 8:00" and// clock(150) is "2:30".std::string format_text(std::span<const WeekTotal> totals, std::span<const SkippedLine> skipped) { std::string out = "Overtime report\n"; // For Ana's first week this adds "Ana week 1 worked 42:30 overtime 2:30". for (const WeekTotal& t : totals) { out += padded(t.person, 6) + " week " + std::to_string(t.week) + " worked " + clock(t.worked_minutes, 2) + " overtime " + clock(t.overtime_minutes) + '\n'; } if (!skipped.empty()) { out += "Skipped lines: "; // ", " before every number except the first: "9, 10". The reasons // are not shown in this format, only the line numbers. for (std::size_t i = 0; i < skipped.size(); ++i) { out += (i == 0 ? "" : ", ") + std::to_string(skipped[i].line_number); } out += '\n'; } return out;}
// The CSV layout: a header row, then one row per week with plain minutes,// for example "Ana,1,2550,150". Skipped lines are not part of this format.std::string format_csv(std::span<const WeekTotal> totals) { std::string out = "person,week,worked_minutes,overtime_minutes\n"; for (const WeekTotal& t : totals) { out += t.person + ',' + std::to_string(t.week) + ',' + std::to_string(t.worked_minutes) + ',' + std::to_string(t.overtime_minutes) + '\n'; } return out;}Orchestration. Three calls and one write:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Input, then the rule, then the chosen format, then one write. Each step// gets the previous step's values; none of them knows about the others.void run_overtime_report(std::istream& in, std::ostream& out, Format format) { const Timesheet sheet = read_timesheet(in); // sheet.entries is a vector; it converts to the span weekly_totals takes. const std::vector<WeekTotal> totals = weekly_totals(sheet.entries); // `?:` picks one format, and only the chosen one is called. out << (format == Format::text ? format_text(totals, sheet.skipped) : format_csv(totals));}Why each choice
Section titled “Why each choice”- Free functions, not classes. None of these parts has an invariant to protect or state that lives between calls, so a class would add a constructor and nothing else. Separation of concerns is about where code lives, not about making classes. If a part later needs state, for example a cache of parsed files, it can become a class then.
- Values between the steps.
format_textreturns astd::stringinstead of writing to a stream. That keeps the decision of where output goes in one place, the orchestrator, and lets a test compare a string directly. For a report of a few hundred lines, building one string is cheap. (For very large output, see “when not to” below.) - Streams chosen by the caller.
run_overtime_reporttakesstd::istream&andstd::ostream&, not a file name and notstd::cout.mainpassesstd::cout; a test passes astd::ostringstream; a future version could pass a file. The function borrows both streams for the length of the call and owns neither. - The
Formatchoice at the top. PassingFormattorun_overtime_reportis control coupling: the caller picks a path inside the function. Cohesion and coupling warns against that, so why is it acceptable here? Because the choice is made once, at the top, where a command-line flag or a menu choice arrives, and it selects one complete function. The two formats share no code paths. The flag would be a problem if it travelled down intoweekly_totalsor intoformat_text. If many formats appear, replace theenum classwith a table of functions or an interface (the next page, on composition and interfaces, covers when that is worth it). - An output parameter for the reason.
parse_entryreturns anstd::optional<Entry>and writes the failure reason into astd::string&. That keeps the example in C++20, but it is a trade-off: the caller must provide a string, and the reason is meaningless when the parse succeeds. With C++23,std::expected<Entry, std::string>returns either the entry or the reason, and is the clearer choice. A smallstruct ParseResultis another option. - Bad lines are data, not exceptions. FR-4 says a bad line must not
stop the report, so bad lines are expected input, not an exceptional
failure. Input returns them in
Timesheet::skipped, and the format decides how to show them.
Check: the same report, then a new format
Section titled “Check: the same report, then a new format”The example program runs the same timesheet through the old function and the new design, then asks the new design for CSV:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A small timesheet as one string. Lines next to each other in quotes// are joined into one string by the compiler. Line 1 is the header.// Line 9 has the letter O in "9:6O", not a zero, and line 10 has "one"// for the week, so both are skipped.const std::string timesheet = "person,week,worked\n" "Ana,1,10:00\n" "Ana,1,10:00\n" "Ana,1,10:00\n" "Ana,1,12:30\n" "Ben,1,7:45\n" "Ben,1,8:15\n" "Ana,2,8:00\n" "Cy,1,9:6O\n" "Ben,one,8:00\n";
// A std::istringstream reads from a string as if it were a file. Reading// uses it up, so each run gets a fresh one made from the same text.std::istringstream first{timesheet};std::cout << "-- before --\n";before::overtime_report(first);
// The new design: the caller chooses the input, the output stream, and// the format. Only the last argument differs between the two runs.std::istringstream second{timesheet};std::cout << "-- after, text --\n";run_overtime_report(second, std::cout, Format::text);
std::istringstream third{timesheet};std::cout << "-- after, csv --\n";run_overtime_report(third, std::cout, Format::csv);-- before --Overtime reportAna week 1 worked 42:30 overtime 2:30Ana week 2 worked 8:00 overtime 0:00Ben week 1 worked 16:00 overtime 0:00Skipped lines: 9, 10-- after, text --Overtime reportAna week 1 worked 42:30 overtime 2:30Ana week 2 worked 8:00 overtime 0:00Ben week 1 worked 16:00 overtime 0:00Skipped lines: 9, 10-- after, csv --person,week,worked_minutes,overtime_minutesAna,1,2550,150Ana,2,480,0Ben,1,960,0The text reports are identical. Ana’s first week is 42:30, so 2:30 is overtime. Line 9 has a letter O in place of a zero, and line 10 has a week written as a word; both are skipped and listed. The CSV shows the same totals as minutes (2550 is 42:30), because a CSV file is read by another program, which should get numbers, not text to parse.
The tests show what the separation buys. The rule is tested with entries made up in the test, with no text at all. Parsing is tested one line at a time. The text format is tested with totals made up in the test. Only the last test runs the whole pipeline, and it checks that the new design prints exactly what the old function printed:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// LLD_TEST(name) defines one test, and LLD_CHECK(condition) records a// failure if the condition is false. Both come from the site's small test// header, lld_test.hpp.
// The rule, with no text and no streams. Each {...} builds an Entry// (person, week, minutes). Ana's week 1 is 25 h + 17 h = 42 h, so 2 h of// overtime; week 2 is 1 h, so none. Two weeks, two totals, in week order.LLD_TEST(overtime_is_time_above_forty_hours_in_one_week) { const std::vector<Entry> entries{{"Ana", 1, 25 * 60}, {"Ana", 1, 17 * 60}, {"Ana", 2, 60}}; const std::vector<WeekTotal> totals = weekly_totals(entries); LLD_CHECK(totals.size() == 2); LLD_CHECK(totals[0].worked_minutes == 42 * 60); LLD_CHECK(totals[0].overtime_minutes == 2 * 60); LLD_CHECK(totals[1].overtime_minutes == 0);}
// The edge: overtime is time *above* 40 hours, so exactly 40 gives none.LLD_TEST(exactly_forty_hours_is_not_overtime) { const std::vector<Entry> entries{{"Ben", 3, 40 * 60}}; LLD_CHECK(weekly_totals(entries)[0].overtime_minutes == 0);}
// Parsing, one line at a time. 9:30 is 9 * 60 + 30 = 570 minutes.// entry->person reads a field of the Entry inside the optional.LLD_TEST(a_line_parses_into_an_entry) { std::string reason; const auto entry = parse_entry("Ana,1,9:30", reason); LLD_CHECK(entry.has_value()); LLD_CHECK(entry->person == "Ana" && entry->week == 1 && entry->minutes == 570);}
// Three bad lines, each failing a different check. The same `reason`// string is reused: each failure overwrites it, so each check sees the// reason for the line just parsed. (9:75 has more than 59 minutes.)LLD_TEST(bad_lines_say_why) { std::string reason; LLD_CHECK(!parse_entry("Ana,1", reason).has_value()); LLD_CHECK(reason == "expected person,week,hours:minutes"); LLD_CHECK(!parse_entry("Ana,x,9:30", reason).has_value()); LLD_CHECK(reason == "week is not a number"); LLD_CHECK(!parse_entry("Ana,1,9:75", reason).has_value()); LLD_CHECK(reason == "time is not hours:minutes");}
// Cases the old function let through, easy to try now that parsing stands alone.// "-1:30" is refused by read_int's '-' check, ",1,9:30" by c1 == 0, and// "Ben,,8:00" because its week field is empty.LLD_TEST(negative_times_and_missing_names_are_refused) { std::string reason; LLD_CHECK(!parse_entry("Ana,1,-1:30", reason).has_value()); LLD_CHECK(reason == "time is not hours:minutes"); LLD_CHECK(!parse_entry(",1,9:30", reason).has_value()); LLD_CHECK(reason == "person is missing"); LLD_CHECK(!parse_entry("Ben,,8:00", reason).has_value()); LLD_CHECK(reason == "week is not a number");}
// Formatting, from values made up in the test: no file and no parsing.// 42 * 60 + 30 = 2550 minutes worked and 150 minutes (2:30) of overtime.// The name is padded to 6 characters, and line 9 is listed as skipped.LLD_TEST(the_text_report_pads_hours_and_lists_skipped_lines) { const std::vector<WeekTotal> totals{{"Ana", 1, 42 * 60 + 30, 150}}; const std::vector<SkippedLine> skipped{{9, "time is not hours:minutes"}}; LLD_CHECK(format_text(totals, skipped) == "Overtime report\n" "Ana week 1 worked 42:30 overtime 2:30\n" "Skipped lines: 9\n");}
// The same kind of values in CSV: plain minutes, no hours:minutes.LLD_TEST(the_csv_report_gives_plain_minutes) { const std::vector<WeekTotal> totals{{"Ana", 1, 42 * 60 + 30, 150}, {"Ben", 1, 16 * 60, 0}}; LLD_CHECK(format_csv(totals) == "person,week,worked_minutes,overtime_minutes\n" "Ana,1,2550,150\n" "Ben,1,960,0\n");}
// The whole pipeline gives what the old function gave, for a sheet with// one overtime week (41:05), one bad line (line 3, "x"), and one short week.LLD_TEST(the_separated_design_prints_what_the_old_function_printed) { const std::string sheet = "person,week,worked\nAna,1,41:05\nBen,2,x\nBen,2,3:00\n"; std::istringstream a{sheet}; std::istringstream b{sheet}; // An ostringstream collects what is written to it; .str() gives it back. std::ostringstream after; run_overtime_report(b, after, Format::text);
// The old function can only write to std::cout, so the test has to // capture std::cout: rdbuf(x) makes std::cout write into x and returns // the buffer it used before, which is put back straight afterwards. // This awkward step is the cost of output being hard-wired. std::ostringstream captured; std::streambuf* old = std::cout.rdbuf(captured.rdbuf()); before::overtime_report(a); std::cout.rdbuf(old);
LLD_CHECK(captured.str() == after.str());}Once parse_entry could be tested on its own, it was easy to try odd
lines, and that showed cases the old function lets through. It accepts
Ana,1,-1:30, because std::from_chars reads -1 as a valid int. It
accepts a line with no name, and a line with an empty week (Ben,,8:00
becomes week 0). Given the first two lines, it prints a row with no name
and a row that says worked 0:-30. The new parse_entry refuses all
three, with a reason, and the test negative_times_and_missing_names_are_refused
keeps it that way. The old function was always wrong here; the cases were
just hard to reach through a function that needs a whole file and prints
to std::cout.
Concerns inside classes
Section titled “Concerns inside classes”Everything above applies to classes as well as to functions. A class that mixes concerns usually shows it in its member functions:
| A class that mixes concerns | Separated |
|---|---|
Order with total_cents(), save_to_database(), and to_html() |
Order keeps the rule (total_cents); an OrderStore saves; a free to_html(const Order&) formats |
Thermostat that reads the sensor hardware inside on_reading |
Thermostat::on_reading(double) takes the value; the caller reads the sensor (as in encapsulation) |
ReportGenerator that holds a file path, parses, calculates, and prints |
the four parts on this page, with the path known only to main |
A useful sign: if a class’s header includes <iostream>, <fstream>, a
database client, and a networking library, and it also contains the core
business rules, it probably has several concerns. The class that holds
the rules should need no I/O or system headers at all.
Separation of concerns also works at larger scales, which later pages cover:
| Scale | What is separated | Covered in |
|---|---|---|
| function | the steps inside one function | this page |
| header and file | which declarations live together | this page |
| class | which data members and functions belong together | the Single Responsibility Principle page |
| layer or module | domain, application, and infrastructure code | the layered architecture page |
When not to
Section titled “When not to”- Short, one-off code. A 20-line tool that runs once to fix a data file does not need four headers. Separate concerns when the code will live, change, or be tested.
- When the concerns never vary independently. If there is only ever one input format and one output, and the rule is one line, splitting may add more names than it removes confusion. Even then, keeping the rule out of the print statement costs almost nothing.
- Very large inputs. The design reads the whole timesheet into memory and builds the whole report as one string. For a file of many gigabytes, that is wrong. The concerns can still be separated, but the parts would pass entries one at a time (for example, input calls a function for each entry, and the rule keeps running totals) instead of passing whole vectors.
- Splitting too finely. A separate function for “skip the header” or “find the second comma” is not a concern; it is a step. Split where the reasons to change differ, not wherever a function could be cut.
Trade-offs
Section titled “Trade-offs”| You gain | You pay |
|---|---|
| the rule can be tested with no text, files, or streams | more functions and more names to learn |
| a new format or input source is one new function | plain records (Entry, WeekTotal) that exist only to carry data |
| a reader finds “what is overtime?” in one place | the flow is spread over files; the orchestrator is the map |
| bad input is reported as data, and each part decides how to treat what it receives | intermediate values use memory (fine here; see “when not to”) |
Common mistakes
Section titled “Common mistakes”- Splitting by step instead of by concern. “Read, then process, then print” functions that each still mix rules and formatting, as in the good-but-not-enough version above.
- Passing streams down. If
format_texttakesstd::ostream&, the format starts deciding when output happens. Passingstd::coutinto the rule is worse: the rule now does output. - Formatting inside input. Collecting errors as display text
(
"9, 10") while reading. Store what happened; format it later. - Rules inside the orchestrator.
run_overtime_reportshould not containif (minutes > 2400). Once it does, there are two places that know the rule. - Reading configuration deep inside. A rule that opens a settings file
to find “40 hours” has an input concern inside it. Pass the number in, or
keep it as a named constant next to the rule, as
regular_minutes_per_weekis here. - Creating a class per concern by reflex. Separation is about where code lives. A free function in its own header is a complete home.
When a requirement changes
Section titled “When a requirement changes”The payroll system asks for CSV, with times as plain minutes. That change is already in the example, so it is worth looking at what it took:
| Part | Changed? |
|---|---|
parse_entry, read_timesheet |
no |
weekly_totals |
no |
format_text |
no |
format_csv |
new, 8 lines |
Format |
one new value, csv |
run_overtime_report |
one line: choose between the two formats |
| tests | existing tests unchanged; one new test for format_csv, with made-up totals |
In the old design, the same request means copying the whole function or adding a flag that runs through it.
Other likely changes land in one place too. Timesheets from a database
instead of a file: a new input function that produces the same Timesheet.
Overtime after 37.5 hours for part-time staff: weekly_totals changes,
and so does wherever the part-time flag comes from (a new field in the
input, or a new input source), but no format changes. A new column
in the text report: only format_text changes.
Exercise: Split a mixed-concern function
A library sends late-fee emails. This function works, but it mixes concerns (the includes are left out):
// Reads loans.csv (member_email,title,days_out). For each loan out more than// 14 days, emails the member: 25 cents per day after day 14, at most 10.00.void send_late_fee_emails(const std::string& path, SmtpClient& smtp) { std::ifstream file{path}; // opens the file for reading std::string line; while (std::getline(file, line)) { // find gives the first comma, rfind the last one, so a title that // itself contains a comma still stays in one piece. const auto c1 = line.find(','); const auto c2 = line.rfind(','); const std::string email = line.substr(0, c1); const std::string title = line.substr(c1 + 1, c2 - c1 - 1); // between the commas // std::stoi turns the text after the last comma into an int. (What // it does with text that is not a number is question 4.) const int days = std::stoi(line.substr(c2 + 1)); if (days <= 14) continue; // not late yet: next line // 25 cents for each day after day 14, but never more than 1000 (10.00). const int cents = std::min((days - 14) * 25, 1000); // Builds the text, for example: "Dune" is 3 days late. Fee: 0.75 // cents / 100 is the whole amount and cents % 100 the cents; a // value under 10 gets ".0" first, so 100 cents shows as "1.00". smtp.send(email, "Late fee", '"' + title + "\" is " + std::to_string(days - 14) + " days late. Fee: " + std::to_string(cents / 100) + (cents % 100 < 10 ? ".0" : ".") + std::to_string(cents % 100)); }}- Do the highlighter test: which concerns does it contain? There are more than four.
- Write the declarations (records and function signatures) of a separated design.
- Which parts can you test without a file and without a mail server?
- What happens today when line 7 of the file has
sevenin place of a number? What should happen? - The front desk now wants a printed list of late loans, without emails. What changes in your design?
Show the explained answer
1. The concerns. Input (opening the file, splitting the line, reading
the number), the domain rule (14 days of grace, 25 cents a day, a cap of
10.00), the output format (the email text and the money format), delivery
(sending the email through SmtpClient), and orchestration (the loop and
the order). Delivery is a fifth concern: it talks to another system.
2. A separated design, as declarations:
// One line of the file, read: plain values, no text to parse later.struct Loan { std::string member_email; std::string title; int days_out = 0;};
// What reading gives back: the good loans and the numbers of bad lines.struct LoanFile { std::vector<Loan> loans; std::vector<int> bad_lines;};
// Input[[nodiscard]] LoanFile read_loans(std::istream& in);
// The ruleinline constexpr int grace_days = 14;inline constexpr int cents_per_late_day = 25;inline constexpr int max_fee_cents = 1000;[[nodiscard]] int late_fee_cents(int days_out); // 0 when not late
// Format[[nodiscard]] std::string late_fee_message(const Loan& loan, int fee_cents);
// Delivery: what orchestration needs from a mail system. An interface:// `= 0` means each kind of mailer must supply its own send, and the// virtual destructor lets one be destroyed safely through a Mailer pointer.class Mailer {public: virtual ~Mailer() = default; virtual void send(const std::string& to, const std::string& subject, const std::string& body) = 0;};
// Orchestration. Returns the numbers of the lines that could not be read.[[nodiscard]] std::vector<int> send_late_fee_emails(std::istream& loans, Mailer& mailer);The rule and the orchestration, to show how small they become:
#include <algorithm> // std::min
// The rule alone: no file, no text, no mail. 15 days gives 25, 54 gives// 1000, and anything longer is capped at 1000.int late_fee_cents(int days_out) { if (days_out <= grace_days) return 0; return std::min((days_out - grace_days) * cents_per_late_day, max_fee_cents);}
// Orchestration: read, then for each loan apply the rule, format, deliver.std::vector<int> send_late_fee_emails(std::istream& in, Mailer& mailer) { const LoanFile file = read_loans(in); for (const Loan& loan : file.loans) { // `if` with an initializer: `fee` is worked out first and exists // only inside this if; the mail is sent only when there is a fee. if (const int fee = late_fee_cents(loan.days_out); fee > 0) { mailer.send(loan.member_email, "Late fee", late_fee_message(loan, fee)); } } return file.bad_lines; // the caller decides how to report them}Mailer is an interface because delivery is a real variation point: the
real program sends mail, and a test records what would have been sent. An
adapter class implements Mailer by calling SmtpClient. Whether an
interface is worth it is the subject of the next page, on composition and
interfaces.
The file name is now known only to whoever opens the file and passes the
stream in.
3. Testable without a file or mail server: late_fee_cents (with
plain numbers: 14 gives 0, 15 gives 25, 54 gives exactly 1000, 100 is
capped at 1000), late_fee_message (with a made-up Loan), and
read_loans (with a std::istringstream). Orchestration can be tested
with a fake Mailer that stores the messages.
4. A bad number. std::stoi("seven") throws std::invalid_argument,
and the exception leaves the loop. The late loans on lines 1 to 6 have
been emailed, and the rest have not. Nothing records how far it got, so
running it again emails those members twice. In the separated design, read_loans
reads the whole file first and returns line 7 in bad_lines, so the
emails go out for every good line, and the bad line number is returned so
the caller can report it.
(Avoiding duplicate emails across runs is a separate storage concern.)
5. The desk list. A new format function, for example
std::string format_desk_list(std::span<const Loan> loans), and a new
small orchestrator that reads the loans, keeps those for which
late_fee_cents returns more than 0, and prints the list. read_loans,
late_fee_cents, and the email code do not change. Both orchestrators ask
the rule whether a loan is late, so “late” is still defined in one place.
If that test grows (say, fees can be waived), give it its own rule
function, such as late_loans(std::span<const Loan>), rather than
repeating fee > 0 in each orchestrator.
In the original function, the desk list would have meant copying the
parsing and the fee rule.
Summary
Section titled “Summary”- A concern is one kind of question code answers, or one reason it changes. Most programs have at least four: input, domain rules, output format, and orchestration.
- Use the highlighter test to find them: mark each line with its concern. Interleaved colours mean tangled concerns.
- Give each concern its own home, and pass plain values between them. Only the orchestrator should decide where input comes from and where output goes.
- Splitting by step is not the same as separating concerns.
- The payoff: the rule is testable with no text or streams, and a new format or input source is one new function.
- Do not separate a 20-line one-off tool into four headers, and do not split steps that change for the same reason.