Skip to content

The Single Responsibility Principle

Difficulty: Intermediate

Key concepts

  • single responsibility principle
  • reason to change
  • actor
  • shared facts and separate rules
  • over-splitting
  • What the Single Responsibility Principle (SRP) says, and why “responsibility” means a reason to change, not “one thing”.
  • How to find the actors (the groups of people who ask for changes) behind each member function of a class.
  • How to split a class along those lines, keeping shared facts in one place and each group’s rules in another.
  • How to decide which data members and functions go into which class.
  • How to avoid the opposite mistake: over-splitting one group’s rules into many tiny classes.

A small company pays its staff weekly. One program does three jobs:

  1. FR-1 (asked for by finance) Pay each person for the hours on their timesheet: up to 40 hours at their hourly rate, anything over 40 at 1.5 times the rate.
  2. FR-2 (asked for by operations, for health and safety) Each week, list everyone who worked more than 40 hours, so their manager can talk to them.
  3. FR-3 (set by the bank) Write a file the bank can import: one line per person, NAME;CENTS.

Last month, finance signed a new agreement: Sunday work is always paid as overtime, however many hours someone works. A developer changed the program, the pay was right, and the next Monday operations asked why Cy, who works 20 hours a week, 16 of them at the weekend, was on the “overworked” list.

The Single Responsibility Principle is usually stated as: a class should have one reason to change.

“Reason to change” is easy to misread, so make it concrete: a reason to change is a person or group who can ask for a change. Call them actors. A class has a single responsibility when one actor is behind all the changes it can need.

SRP is the “S” in SOLID, a set of five principles that the next pages of this section cover one by one.

It does not mean It does mean
“A class does one thing” (one function per class) All of a class’s rules answer to the same group of people
“A function does one thing” SRP is about classes and modules; “a function does one thing” is a separate guideline
“Make classes as small as possible” Keep together what changes together; split what changes for different people
“Each class has one public function” A class can have many functions, if one actor is behind all of them

Why actors, not “things”? Because “one thing” depends on how you squint: “handle payroll” is one thing, and so is “add two numbers”. Asking who would ask for this to change gives a much steadier answer, though naming the actors still takes judgment.

Step 1: name the actor behind every member

Section titled “Step 1: name the actor behind every member”

Here is the program’s main class:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

before.hpp
// Before: one class serves three groups of people. Finance owns the pay
// rules, operations owns the workload check, and the bank owns the file
// format. All three live here, and two share a helper.
namespace before {
// One stretch of work: which day, and how many minutes. Day is an enum
// class of the seven weekdays, monday to sunday (day.hpp).
struct Shift {
Day day;
int minutes;
};
// An employee's week, plus every rule anyone has about it. Nothing here
// checks its input: a negative rate or a 30-hour day is accepted.
class Employee {
public:
// The name is taken by value and moved into name_, so a caller's
// string is copied once at most (see the idiom reference on std::move).
Employee(std::string name, int hourly_cents)
: name_{std::move(name)}, hourly_cents_{hourly_cents} {}
// {day, minutes} builds a Shift from its two fields, in order, and
// push_back appends it to the list of shifts.
void add_shift(Day day, int minutes) { shifts_.push_back({day, minutes}); }
[[nodiscard]] int pay_cents() const; // finance
[[nodiscard]] bool overworked() const; // operations: more than 40 hours?
[[nodiscard]] std::string payroll_line() const; // the bank's import format
private:
[[nodiscard]] int total_minutes() const; // all shifts added up
// Shared by pay and overworked: one helper, two groups' rules. This
// private line is where the bug below comes from.
[[nodiscard]] int overtime_minutes() const;
std::string name_;
int hourly_cents_;
std::vector<Shift> shifts_;
};
} // namespace before

Before changing anything, list every member and ask who would ask for it to change:

Member What it is Who asks for changes
name_, shifts_ facts about the week nobody’s rule; changes only if the facts recorded change
hourly_cents_ a fact used by pay finance (rates are part of the pay agreement)
pay_cents() a rule finance
overworked() a rule operations
payroll_line() a format the bank
total_minutes() a fact, computed nobody’s rule
overtime_minutes() a rule, shared finance and operations

Three actors in one class. And the last row is where the bug came from: one private helper serves two actors.

The before and after, as outlines:

class Employee

finance, operations, and the bank all change this

Data members

  • std::string name_;
  • int hourly_cents_; finance
  • std::vector<Shift> shifts_;
  • int total_minutes() const;
  • int overtime_minutes() const; shared by finance and operations

Member functions

  • Employee(std::string name, int hourly_cents);
  • void add_shift(Day day, int minutes);
  • int pay_cents() const; finance
  • bool overworked() const; operations
  • std::string payroll_line() const; the bank
Before: one class with three actors behind it, and a helper shared by two of them

class Timesheet

facts only; no actor's rules

Data members

  • std::string employee_; never empty
  • std::array<int, 7> minutes_by_day_; each day at most 24 hours

Member functions

  • explicit Timesheet(std::string employee);
  • void add_shift(Day day, int minutes); throws on impossible shifts
  • const std::string& employee() const;
  • int minutes_on(Day day) const;
  • int total_minutes() const;

namespace pay

finance

Constants

  • constexpr int standard_week_minutes = 40 * 60;

Functions

  • int overtime_minutes(const Timesheet& week);
  • int weekly_pay_cents(const Timesheet& week, int hourly_cents); throws if the rate is negative

namespace workload

operations

Constants

  • constexpr int limit_minutes = 40 * 60;

Functions

  • bool over_limit(const Timesheet& week);
  • std::vector<std::string> overworked(const std::vector<Timesheet>& weeks);

namespace bank_export

the bank

Functions

  • std::string line(std::string_view employee, int cents);
After: one class of facts, and three groups of rules, one per actor

The facts:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

timesheet.hpp
// Facts only: who worked how long on which day this week. No pay rules,
// no workload rules, no file formats, so no group's change lands here
// unless the facts themselves change.
//
// Invariant (a rule that is true for every Timesheet you can get hold
// of): the name is not empty, and no day holds more than 24 * 60 = 1440
// minutes. The constructor and add_shift check it, so code that reads a
// Timesheet never has to.
class Timesheet {
public:
// Throws std::invalid_argument if the name is empty. `explicit` stops a
// plain string being turned into a Timesheet without anyone asking.
explicit Timesheet(std::string employee);
// Adds minutes to that day's total. Throws std::invalid_argument if
// minutes < 1, or if the day would then have more than 24 hours. The
// check comes before the change, so a refused shift leaves the
// timesheet exactly as it was.
void add_shift(Day day, int minutes);
// A const reference: the caller reads the stored name without a copy.
// It stays valid only while this Timesheet exists.
[[nodiscard]] const std::string& employee() const { return employee_; }
[[nodiscard]] int minutes_on(Day day) const; // 0 for a day not worked
[[nodiscard]] int total_minutes() const; // all seven days added up
private:
std::string employee_;
// One total per day, not a list of shifts: every rule today needs only
// minutes per day. Day::monday is index 0, ..., Day::sunday is index 6
// (the .cpp turns a Day into its number with static_cast). The `{}`
// starts all seven totals at 0.
std::array<int, 7> minutes_by_day_{};
};

Finance’s rules:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

pay.hpp
// Finance's rules. Changes when the pay agreement changes.
namespace pay {
// Finance's standard week: 40 hours, 2400 minutes. `inline constexpr` is
// a constant fixed at compile time that can live in a header: every file
// that includes this header shares the one definition.
inline constexpr int standard_week_minutes = 40 * 60;
// Sunday minutes, plus any other minutes beyond the standard week. Reads
// the timesheet through a const reference: no copy, no changes.
[[nodiscard]] int overtime_minutes(const Timesheet& week);
// Regular time at the hourly rate, overtime at 1.5 times; rounded down
// to the cent. Throws std::invalid_argument if hourly_cents < 0. The rate
// is a parameter because it is finance's data, not a fact of the week.
[[nodiscard]] int weekly_pay_cents(const Timesheet& week, int hourly_cents);
} // namespace pay

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

pay.cpp
// The same rule as the old helper, now owned by finance alone. Every
// Sunday minute counts, plus the non-Sunday minutes beyond 2400;
// std::max(0, ...) keeps a short week from giving negative overtime.
int overtime_minutes(const Timesheet& week) {
const int sunday = week.minutes_on(Day::sunday);
return sunday + std::max(0, week.total_minutes() - sunday - standard_week_minutes);
}
// Refuse a negative rate first, then split the week into overtime and
// regular minutes, and price both over a common 120 (see the walkthrough
// below the code): regular is rate * 2 / 120 a minute, overtime rate * 3 /
// 120. long long is a wider integer, so the products cannot overflow an
// int; the single division at the end rounds down to a whole cent.
int weekly_pay_cents(const Timesheet& week, int hourly_cents) {
if (hourly_cents < 0) throw std::invalid_argument("hourly rate cannot be negative");
const long long overtime = overtime_minutes(week);
const long long regular = week.total_minutes() - overtime;
return static_cast<int>((regular * hourly_cents * 2 + overtime * hourly_cents * 3) / 120);
}
How this code works: pay::overtime_minutes and pay::weekly_pay_cents

Follow Cy’s week through both functions: 240 minutes on Monday, 480 on Saturday, 480 on Sunday, at 1800 cents (18.00) an hour.

  1. Overtime. minutes_on(Day::sunday) is 480. The rest of the week is 1200 - 480 = 720 minutes, which is not more than 2400, so std::max(0, 720 - 2400) is 0. Overtime is 480 + 0 = 480 minutes.
  2. Regular time is everything else: 1200 - 480 = 720 minutes.
  3. Pricing over 120. A minute of regular time is worth rate / 60 cents, and a minute of overtime rate * 1.5 / 60. Multiplying top and bottom by 2 gives rate * 2 / 120 and rate * 3 / 120: the same values, with no fraction. So the code adds the two tops and divides once:
Part Calculation Value
regular top 720 * 1800 * 2 2,592,000
overtime top 480 * 1800 * 3 2,592,000
sum 5,184,000
divided by 120 5,184,000 / 120 43,200

That is 432.00: 12 hours at 18.00 (216.00) plus 8 hours at 27.00 (216.00). The test sunday_is_overtime_for_pay_but_not_for_workload checks this number.

  1. Rounding. Integer division drops any remainder, so pay is rounded down to the cent, once, at the end. One regular minute at 1999 cents an hour is 1 * 1999 * 2 / 120 = 3998 / 120, which is 33 (33.3 dropped to 33).
  2. Why long long. The tops are minutes times cents times 3. A week can hold up to 10,080 minutes, so with a large rate the product could pass the largest int (about 2.1 billion). Holding the minutes as long long makes every multiplication use the wider type.

overtime_minutes is called by weekly_pay_cents and by nothing in operations’ code. That is the point of the split: finance can change it, and only pay changes.

Operations’ rule:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

workload.hpp
// Operations' rule. Changes when the health-and-safety policy changes.
namespace workload {
// The same number as pay::standard_week_minutes today, but a different
// decision by different people, so it is not shared (see DRY).
inline constexpr int limit_minutes = 40 * 60;
// True if the week's total, whatever the days, is more than the limit.
// `>` rather than `>=`: exactly 40 hours is not over. Sunday minutes count
// like any others here, because this rule is about time worked, not pay.
// `inline` lets a function body sit in a header that many files include.
[[nodiscard]] inline bool over_limit(const Timesheet& week) {
return week.total_minutes() > limit_minutes;
}
// Names of everyone over the limit, in the order given. Returns a new
// vector of copies of the names; the timesheets are only read.
[[nodiscard]] std::vector<std::string> overworked(const std::vector<Timesheet>& weeks);
} // namespace workload

The bank’s format:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

bank_export.hpp
// The bank's import format: "NAME;CENTS". Changes when the bank says so.
namespace bank_export {
// Builds one line of the file, for example line("Ana", 80000) gives
// "Ana;80000". Throws std::invalid_argument if the name contains ';' or a
// line break, which the format cannot hold (a ';' would look like the end
// of the name), or if cents is negative. std::string_view is a read-only
// view of someone else's characters, so passing a name copies nothing.
[[nodiscard]] std::string line(std::string_view employee, int cents);
} // namespace bank_export

Shared facts are safe; shared rules are not

Section titled “Shared facts are safe; shared rules are not”

Every actor still uses Timesheet. Is that not the same sharing that caused the bug? No, and the difference is the most useful idea on this page:

  • A fact (“Cy worked 480 minutes on Sunday”) is true for everyone. If it changes, it is because the world changed, and every reader should see the new value.
  • A rule (“Sunday minutes count as overtime”) belongs to whoever decided it. If it changes, only that group’s results should change.

So a class may serve many actors if it holds only facts. The trouble starts when one actor’s rule hides inside it. Timesheet has an invariant (no day longer than 24 hours), and that is a fact about time, not a rule anyone can renegotiate.

This is the “how do I decide which class gets which member?” question, answered for this example:

Old member New home Why there
name_ Timesheet::employee_ A fact about whose week it is. The constructor refuses an empty name, so the class keeps one invariant itself.
shifts_ Timesheet::minutes_by_day_ Every current rule needs only minutes per day, so the class stores exactly that, and checks the 24-hour limit as shifts are added.
hourly_cents_ a parameter of pay::weekly_pay_cents The rate is finance’s data, not a fact about the week. A full program would keep it in finance’s own records (a pay agreement per person); the example passes it in.
total_minutes() Timesheet::total_minutes() A fact computed from facts. Safe for everyone to share.
overtime_minutes() pay::overtime_minutes() Finance’s definition. Operations no longer calls it, so finance can change it freely.
pay_cents() pay::weekly_pay_cents() Finance’s rule.
overworked() workload::over_limit() Operations’ rule, written in operations’ own terms: total time, whatever the day.
payroll_line() bank_export::line() The bank’s format, including what the format cannot hold (a ; in a name, a negative amount).

Three more choices worth naming:

  • Namespaces of free functions, not classes, for the rules. pay, workload, and bank_export hold no state of their own, so a class would add nothing but a constructor. When a group’s rules gain configuration (say, different agreements for different contracts), that is the moment to make a PayAgreement class that holds it.
  • Two 40 * 60 constants. pay::standard_week_minutes and workload::limit_minutes are equal today. Sharing one constant would rebuild the bug: the next time finance changes its number, operations’ would change too. Equal values, different decisions.
  • SRP is about modules, not only classes. Here a “responsibility” lands in a namespace and a pair of files. The principle is the same for a class, a file, or a library: one actor behind each.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

main.cpp
// `people` (defined above main, not shown) lists each person's name,
// hourly rate in cents, and shifts as (day, minutes) pairs: Ana 5 x 8 h,
// Ben 5 x 9 h, Cy 4 h Monday, 8 h Saturday, 8 h Sunday.
std::cout << "-- after: facts, pay, workload, bank format --\n";
std::vector<Timesheet> weeks; // kept for the workload report at the end
for (const Person& person : people) {
// Record the facts first. Timesheet{person.name} copies the name.
Timesheet week{person.name};
// Each shift is a std::pair; `const auto& [day, minutes]` unpacks
// it into two names (a structured binding).
for (const auto& [day, minutes] : person.shifts) week.add_shift(day, minutes);
// Finance works out the pay from the facts plus the rate, and the
// bank's format turns name and pay into one line. Each module is
// called with only what it needs.
std::cout << bank_export::line(week.employee(), pay::weekly_pay_cents(week, person.hourly_cents))
<< '\n';
// std::move hands this timesheet to the vector instead of copying
// it; `week` is not used again after this line.
weeks.push_back(std::move(week));
}
// Operations' report reads the same facts with its own rule. The
// vector of names it returns is a temporary, and a range-for keeps a
// temporary alive until the loop ends, so this is safe.
std::cout << "over the workload limit:";
for (const std::string& name : workload::overworked(weeks)) std::cout << ' ' << name;
std::cout << '\n';
Expected output
-- before: one Employee class --
Ana;80000
Ben;95000 overworked
Cy;43200 overworked
-- after: facts, pay, workload, bank format --
Ana;80000
Ben;95000
Cy;43200
over the workload limit: Ben

Everyone’s pay is the same in both designs. Only the workload report differs: before, Cy (20 hours, 8 of them on Sunday) is reported as overworked; after, only Ben (45 hours) is.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_payroll.cpp
// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure
// if the condition is false, and LLD_CHECK_THROWS(expression, type) fails
// unless the expression throws that type of exception. They come from the
// site's small test header, lld_test.hpp.
//
// weekend_worker() is a helper defined above (not shown). It returns Cy's
// week as a Timesheet: 4 h Monday, 8 h Saturday, 8 h Sunday, 20 h in all.
// The bug, pinned: finance's Sunday rule changed operations' report. Cy
// works only 20 hours, yet the old class says "overworked", because 8 of
// those hours are on Sunday.
LLD_TEST(before_calls_a_twenty_hour_week_overworked) {
before::Employee cy{"Cy", 1800};
cy.add_shift(Day::monday, 240);
cy.add_shift(Day::saturday, 480);
cy.add_shift(Day::sunday, 480);
LLD_CHECK(cy.overworked());
}
// The fix: the same week is overtime for finance (all 480 Sunday minutes)
// but well under operations' limit (1200 minutes is not over 2400).
LLD_TEST(sunday_is_overtime_for_pay_but_not_for_workload) {
const Timesheet week = weekend_worker();
LLD_CHECK(pay::overtime_minutes(week) == 480);
LLD_CHECK(pay::weekly_pay_cents(week, 1800) == 43200); // 12 h x 18.00 + 8 h x 27.00
LLD_CHECK(!workload::over_limit(week));
}
// Ben: five 9-hour weekdays, 2700 minutes, so 300 beyond 2400. Pay is
// 2400 min x 20.00 an hour = 800.00, plus 300 min x 30.00 an hour =
// 150.00, so 95000 cents. Both groups agree Ben is over 40 hours.
LLD_TEST(minutes_beyond_forty_hours_are_overtime) {
Timesheet week{"Ben"};
// A brace list of Days: the loop runs once for each of the five.
for (const Day day : {Day::monday, Day::tuesday, Day::wednesday, Day::thursday, Day::friday}) {
week.add_shift(day, 540);
}
LLD_CHECK(pay::overtime_minutes(week) == 300);
LLD_CHECK(pay::weekly_pay_cents(week, 2000) == 95000);
LLD_CHECK(workload::over_limit(week));
}
// The edge of the limit: five 8-hour days are exactly 2400 minutes. The
// limit is "more than 40 hours", so this is not over it, and no overtime.
LLD_TEST(exactly_forty_hours_is_not_over_the_limit) {
Timesheet week{"Ana"};
for (const Day day : {Day::monday, Day::tuesday, Day::wednesday, Day::thursday, Day::friday}) {
week.add_shift(day, 480);
}
LLD_CHECK(!workload::over_limit(week));
LLD_CHECK(pay::overtime_minutes(week) == 0);
}
// The split moved code without changing finance's results: the old class
// and the new pay function give Cy the same pay (43200 cents).
LLD_TEST(pay_is_unchanged_by_the_split) {
before::Employee cy{"Cy", 1800};
cy.add_shift(Day::monday, 240);
cy.add_shift(Day::saturday, 480);
cy.add_shift(Day::sunday, 480);
LLD_CHECK(cy.pay_cents() == pay::weekly_pay_cents(weekend_worker(), 1800));
}
// A negative rate makes no sense, so pay throws rather than return one.
LLD_TEST(pay_refuses_a_negative_rate) {
LLD_CHECK_THROWS(pay::weekly_pay_cents(weekend_worker(), -1), std::invalid_argument);
}
// The timesheet's invariant: 20 h on Monday is fine, but 5 h more would
// make 25 h in one day; a 0-minute shift and an empty name are refused
// too. The last check proves the refused shift changed nothing.
LLD_TEST(timesheets_refuse_impossible_shifts) {
Timesheet week{"Ana"};
week.add_shift(Day::monday, 20 * 60);
LLD_CHECK_THROWS(week.add_shift(Day::monday, 5 * 60), std::invalid_argument); // 25 h
LLD_CHECK_THROWS(week.add_shift(Day::tuesday, 0), std::invalid_argument);
LLD_CHECK_THROWS(Timesheet{""}, std::invalid_argument);
LLD_CHECK(week.minutes_on(Day::monday) == 20 * 60); // the refused shift left no trace
}
// One good line, then the two things the format cannot hold. line() is
// [[nodiscard]], so (void) says "result ignored on purpose" (the macro
// also discards it itself).
LLD_TEST(the_bank_format_refuses_what_it_cannot_hold) {
LLD_CHECK(bank_export::line("Ana", 80000) == "Ana;80000");
LLD_CHECK_THROWS((void)bank_export::line("Smith; Jo", 100), std::invalid_argument);
LLD_CHECK_THROWS((void)bank_export::line("Ana", -1), std::invalid_argument);
}

The first test pins the old bug, so the story above is checked, not just told. The others check each actor’s rules on their own: Sunday minutes count for pay but not for workload; exactly 40 hours is not over the limit; minutes beyond 40 hours on weekdays are overtime; pay did not change in the split (for Cy’s week); the timesheet refuses impossible shifts; pay refuses a negative rate; the bank format refuses what it cannot hold.

  • Pay is rounded down to the cent. The intermediate sum uses long long, so it cannot overflow, but the result is an int: for absurd rates (above about 9 million cents an hour) the conversion would overflow. A real payroll would check an upper limit on the rate and use a money type.
  • A shift is only “minutes on a day”. A shift that crosses midnight must be entered as two shifts.
  • The bank format is simplified: real formats have headers, dates, and account numbers.

SRP tells you where to split; it also tells you where not to. Here is finance’s rules, split “one thing per class”:

class SundayMinuteCounter

finance

Member functions

  • int count(const Timesheet& week) const;

class WeekdayOvertimeCalculator

finance

Member functions

  • int overtime(const Timesheet& week, int sunday_minutes) const;

class OvertimeMultiplier

finance

Member functions

  • int apply(int minutes, int hourly_cents) const;

class PayAssembler

finance; calls all three

Member functions

  • int pay(const Timesheet& week, int hourly_cents) const;
Too far: finance's one set of rules spread over four classes that mostly change together

Every one of these has the same actor. When finance changes the agreement (“double time after 50 hours”), three of the four change together (the calculator, the multiplier, and the assembler), and a reader must open four files to see one rule. This is low cohesion: one reason to change, spread out. The pay namespace, with two functions, is the right size. Small private helper functions inside pay are still fine; the mistake is separate public classes for what is one actor’s one rule.

A quick test for over-splitting: if two classes always change in the same commit, for the same person, they are probably one responsibility.

  • One actor. A tool written by one team for its own use may have one actor behind everything. Splitting by actor then gives one piece; keep the facts apart from the rules anyway, because that costs little.
  • Not yet known. If you cannot name who would ask for a change, you cannot split by actor yet. Write the simple version and split when the second actor appears (see YAGNI on the DRY, KISS, and YAGNI page).
  • Tiny programs. A 50-line script that computes one report does not need four modules. SRP pays off when several groups change the code over months or years.
You gain You pay
A change for one group cannot silently change another group’s results More files and names; the code for “pay someone” is in several places
Each group’s rules can be read and tested on their own Callers (here main) must put the pieces together
Can mean fewer merge conflicts between teams Some repetition that looks like duplication but is not (the two 40 * 60)
  • Reading “one thing” instead of “one actor”. It leads to classes with one function each, and to arguments about what “one thing” means.
  • Sharing a helper between actors because the code is identical. The helper is exactly where one group’s change leaks into another’s results.
  • Putting a rule in the “facts” class for convenience. An is_overtime() member on Timesheet looks tidy, but it puts finance’s rule in the class every actor shares.
  • Splitting by technical layer only. “Data class, logic class, output class” can still mix actors inside the logic class. Ask who changes each rule.
  • Over-splitting. Four classes that always change together for one actor are one responsibility.

The bank’s version 2 format: amount first, then the name in capitals. Only bank_export::line changes (compiled sketch, not part of the example):

// Version 2 of the bank's line: "80000;ANA" instead of "Ana;80000". The
// refusals are unchanged; only the order and the capitals are new.
[[nodiscard]] std::string line(std::string_view employee, int cents) {
// find_first_of looks for any one of ';', '\n', '\r' and returns its
// position, or std::string_view::npos ("not found") if none is there.
if (employee.find_first_of(";\n\r") != std::string_view::npos) {
throw std::invalid_argument("name cannot be written in the bank format");
}
if (cents < 0) throw std::invalid_argument("the bank format has no negative amounts");
// A string_view cannot be changed, so copy the name into a string first.
std::string name{employee};
// `char&` is a reference to each character in turn, so assigning to
// `letter` changes the string itself, not a copy.
for (char& letter : name) {
// In ASCII, 'a' to 'z' and 'A' to 'Z' are each in order, so
// letter - 'a' is the letter's place in the alphabet (0 for 'a')
// and adding 'A' gives the capital. The sum is an int, so
// static_cast<char> turns it back into a character.
if (letter >= 'a' && letter <= 'z') letter = static_cast<char>(letter - 'a' + 'A');
}
return std::to_string(cents) + ";" + name; // amount first now
}

(The capitals loop handles only the letters a to z, which is enough for this bank’s format; names with other letters would need a decision from the bank.) The bank’s tests and the expected output change with the format; the pay and workload rules, and their tests, do not. (The sketch leaves out its includes, <stdexcept> and <string>.)

Operations lowers its limit to 38 hours. Only workload::limit_minutes changes. Pay is untouched, which is exactly what the separate constant protects.

Night shifts (22:00 to 06:00) are paid 25% more. This one is harder, and honest about SRP’s limits: finance’s new rule needs a fact the timesheet does not record, the time of day each shift started. So Timesheet changes too (to store shifts with start times), and so does its invariant. That is fine: the facts changed, and every actor sees the richer facts. Operations’ rule still only asks for total_minutes() and does not change.

Exercise: Find the actors behind a class

A library’s program has this class:

class LibraryMember

Data members

  • std::string name_;
  • std::string email_;
  • std::vector<Loan> loans_;

Member functions

  • int fine_cents(std::chrono::sys_days today) const;
  • bool can_borrow(std::chrono::sys_days today) const;
  • std::string card_text() const;
  • std::string overdue_email(std::chrono::sys_days today) const;
  • std::string to_json() const;
A library member class with many jobs

The last year’s change requests for it:

  • The council raised the daily fine, and capped it at 10.00.
  • The head librarian said members with fines over 5.00 may not borrow.
  • The print shop changed the card printer, so the card layout changed.
  • Marketing rewrote the overdue email and added the library’s logo.
  • The web team renamed two fields in the JSON for the new app.
  1. Group the five public functions by actor.
  2. Which data members are facts that several actors share?
  3. Propose a split. Which pieces may call which?
  4. Two functions both need the fine total. Does that mean they should share a helper?
Show the explained answer

1. fine_cents: the council. can_borrow: the head librarian. card_text: the print shop. overdue_email: marketing. to_json: the web team. Five functions, five actors.

2. name_, email_, and loans_ are facts: who the member is and what they have borrowed, with due dates. Several actors read them; none of them decides them.

3. One possible split: a Member class that holds the facts (and checks their invariants, such as a valid email address), and one place per actor: fines::owed(member, today) for the council’s rule, lending::can_borrow(member, today) for the librarian’s, card_layout, overdue_email, and member_json for the three formats. The formats may call the rules to get values to show (the email shows the fine owed); rules should not call formats.

4. can_borrow and overdue_email both need the fine total. That is fine if they both call the council’s fines::owed: the total is the council’s rule, and both want the council’s answer. The danger is the opposite: if the librarian’s rule had its own idea of a “fine” (say, ignoring fines under 1.00), it must be written in lending, not slipped into fines::owed, or the council’s figures would change. Ask the question from the payroll story: if this rule changes, whose results should change?

This is not the payroll mistake in a new form. Operations’ “overworked” was never defined as finance’s overtime; the two only happened to share a number. The librarian’s rule is defined in terms of the council’s fine (“no borrowing with more than 5.00 owed”), so when the council changes how fines are counted, can_borrow changing too is intended.

  • SRP: a class (or module) should have one reason to change, and a reason to change is an actor, a group of people who ask for changes.
  • Find the actor behind every member. A class with several actors, or a helper shared between actors, is where one group’s change silently breaks another’s results.
  • Split by actor: shared facts in one class, each group’s rules in their own place. Facts are safe to share; rules are not.
  • Equal values owned by different actors (the two 40 * 60 constants) stay separate.
  • Do not over-split: things that always change together for the same actor belong together.