Invariants and encapsulation
What you will learn on this page
Section titled “What you will learn on this page”- What a class invariant is, and how to write one down.
- How the constructor makes an invariant true, and how every member function keeps it true.
- Why “a getter and a setter for every field” lets callers break the rules.
- How to test invariants, including after refused operations.
What an invariant is
Section titled “What an invariant is”An invariant is a rule about an
object that is true whenever code outside the class can look at it: after
the constructor finishes, and before and after every public member function.
Earlier lessons have used invariants without much ceremony: a Money amount
cannot be confused with a count of days; an EmailAddress always holds one @;
a placed order has at least one line. This lesson makes them the centre of the
design.
Invariants matter because every other piece of code can rely on them. If the balance is never negative, no caller has to check it. If the history always adds up to the balance, any report built from the history is right. Each rule that the class guarantees is a check that its users never write, and so can never forget.
Encapsulation is what makes the
guarantee possible. The data is private, so only the class’s own member
functions can change it. If those functions keep the rules, the rules hold,
whatever any caller does. If the data were public, the rules would hold only
while every caller in the program behaved.
The example: a basic bank account
Section titled “The example: a basic bank account”A basic account, with no overdraft and no fees. The owner deposits and withdraws money. There is a limit on how much can be withdrawn in one day. The account can be closed only when it is empty, and a closed account accepts nothing more.
Step 1: write the invariants down
Section titled “Step 1: write the invariants down”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// One entry in the account's history. Money is counted in whole cents in a// 64-bit integer (std::int64_t), never in a double, so sums are exact:// $300.00 is 30'000 (the ' only makes long numbers easier to read).struct Transaction { int day; // day number since the account opened std::int64_t amount_cents; // positive: deposit; negative: withdrawal};
// How a request ended: done, or refused for one named reason. Refusals are// a normal part of using an account, so they are returned, not thrown.enum class Outcome { done, account_closed, insufficient_funds, over_daily_limit, still_has_money };
// Invariants, true after every public function returns:// 1. balance_cents() == the sum of every amount in history();// 2. balance_cents() >= 0 (no overdraft);// 3. history() is in day order;// 4. on any one day, withdrawals total at most daily_limit_cents();// 5. a closed account has a zero balance and records nothing more.class Account {public: // Throws std::invalid_argument if daily_limit_cents <= 0. // A new account is open, with a zero balance and an empty history. Account(std::string owner, std::int64_t daily_limit_cents);
[[nodiscard]] const std::string& owner() const noexcept { return owner_; } [[nodiscard]] std::int64_t balance_cents() const noexcept { return balance_cents_; } [[nodiscard]] std::int64_t daily_limit_cents() const noexcept { return daily_limit_cents_; } [[nodiscard]] bool is_open() const noexcept { return open_; } // A const reference: callers can read the history without copying it, // but cannot change it. [[nodiscard]] const std::vector<Transaction>& history() const noexcept { return history_; }
// Both throw std::invalid_argument if amount_cents <= 0, or if day is // earlier than the last recorded day. Refusals change nothing. // amount_cents is always positive: withdraw records it as a negative // amount itself. The arguments are checked before anything else, so a // bad argument throws even when the account is closed. [[nodiscard]] Outcome deposit(int day, std::int64_t amount_cents); [[nodiscard]] Outcome withdraw(int day, std::int64_t amount_cents);
// Refused while money remains: the owner must withdraw it first. // Closing a closed account returns account_closed. [[nodiscard]] Outcome close();
// Checks every invariant from scratch. Used by tests and by assert(). [[nodiscard]] bool invariants_hold() const;
private: // Private helpers, used only by the public functions above: // throws std::invalid_argument for a bad amount or an out-of-order day; void check_arguments(int day, std::int64_t amount_cents) const; // the total withdrawn on `day`, as a positive number of cents; [[nodiscard]] std::int64_t withdrawn_on(int day) const; // appends one transaction and updates the balance to match. void record(int day, std::int64_t amount_cents);
std::string owner_; std::int64_t daily_limit_cents_; std::int64_t balance_cents_ = 0; // stored for speed; must match history_ std::vector<Transaction> history_; // oldest first bool open_ = true;};The header comment lists five invariants, numbered so that the code can refer to them. Writing them down is the most useful step on this page. Each one turns a vague expectation (“the account should be consistent”) into a sentence that is either true or false, and that a test can check.
Notice where each invariant comes from:
- 2, 4, and 5 are business rules: no overdraft, a daily limit, closed means closed.
- 3 is about the data: the history reads as a timeline, so a statement printed from it is in order, and a withdrawal cannot be back-dated.
- 1 exists because of a design choice. The balance could be computed by
adding up the history every time it is asked for. Storing it separately makes
balance_cents()fast, and creates a rule that the two must agree. Every piece of stored data that could be worked out from other stored data creates an invariant. Sometimes that is worth it; sometimes computing the value is simpler.
Step 2: the constructor makes the invariants true
Section titled “Step 2: the constructor makes the invariants true”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The members are set first (balance 0, empty history, open, from their// defaults in the class), which already makes every invariant true. The// one thing left to check is the limit. Throwing from a constructor means// no Account object is created at all, so a caller can never hold one with// a useless limit.Account::Account(std::string owner, std::int64_t daily_limit_cents) : owner_(std::move(owner)), daily_limit_cents_(daily_limit_cents) { if (daily_limit_cents_ <= 0) { throw std::invalid_argument("Account: daily limit must be positive"); } // assert(condition) stops the program with a message if the condition // is false, but only in debug builds: with NDEBUG defined (a release // build) the whole line is removed. assert(invariants_hold());}A new account has no history and a zero balance, so invariants 1 to 5 are true
as soon as the members are initialised, except for one thing the constructor
must check: a daily limit of zero or less would make every withdrawal fail,
which is surely a caller’s mistake. The constructor refuses it with an
exception, so an Account object with a useless limit never exists. That is
the rule from the errors lesson: if a constructor cannot make the invariants
true, it throws.
Step 3: every change keeps them true
Section titled “Step 3: every change keeps them true”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Three stages, in this order: reject caller mistakes (throw), check the// business rules (return a refusal), and only then change anything.Outcome Account::withdraw(int day, std::int64_t amount_cents) { check_arguments(day, amount_cents); // throws on a bad amount or day if (!open_) { return Outcome::account_closed; } if (amount_cents > balance_cents_) { return Outcome::insufficient_funds; // keeps invariant 2 } // What was already taken out today, plus this request, must stay within // the limit. Reaching the limit exactly is allowed (`>` not `>=`). if (withdrawn_on(day) + amount_cents > daily_limit_cents_) { return Outcome::over_daily_limit; // keeps invariant 4 } record(day, -amount_cents); // the minus sign makes it a withdrawal assert(invariants_hold()); return Outcome::done;}
// close has no arguments to check, so it starts at the business rules.Outcome Account::close() { if (!open_) { return Outcome::account_closed; } if (balance_cents_ != 0) { return Outcome::still_has_money; // keeps invariant 5 } open_ = false; assert(invariants_hold()); return Outcome::done;}How this code works: Account::withdraw and close, call by call
Each call goes through its checks from the top, and the first one that fails
decides the result. Only a call that passes them all reaches the line that
changes anything: record for a deposit or withdrawal, open_ = false for
close.
Here are the eight calls the example program makes below, on an account with a
daily limit of $200.00 (amounts in the code are in cents, so $200.00 is
20'000).
| Call | Open? | More than the balance? | Today’s total + amount over $200? | Result | Balance after |
|---|---|---|---|---|---|
| deposit $300.00, day 1 | yes | (not checked) | (not checked) | done |
$300.00 |
| withdraw $150.00, day 2 | yes | $150 vs $300: no | $0 + $150 = $150: no | done |
$150.00 |
| withdraw $100.00, day 2 | yes | $100 vs $150: no | $150 + $100 = $250: yes | over_daily_limit |
$150.00 |
| withdraw $200.00, day 3 | yes | $200 vs $150: yes | (not reached) | insufficient_funds |
$150.00 |
| close | yes | balance is not zero | still_has_money |
$150.00 | |
| withdraw $150.00, day 3 | yes | $150 vs $150: no (equal) | $0 + $150 = $150: no | done |
$0.00 |
| close | yes | balance is zero | done, now closed |
$0.00 | |
| deposit $10.00, day 4 | no | (not reached) | (not reached) | account_closed |
$0.00 |
Three details are worth noticing:
- The order of the checks. The day-3 withdrawal of $200.00 is within the
daily limit, but the balance check comes first, so the answer is
insufficient_funds. - “Today’s total” counts only successful withdrawals. The refused $100.00 on day 2 was never recorded, so it does not count against any later limit. On day 3 the total starts again at $0.
- Arguments are checked before the account is.
check_argumentsruns first, so a negative amount throwsstd::invalid_argumenteven on a closed account, instead of returningaccount_closed. The last deposit has a good amount and day 4 is not earlier than day 3, so it gets as far as the “open?” check.
deposit and withdraw each do three things in order (close does the
same, with no arguments to check):
- Reject caller mistakes, a non-positive amount or a day earlier than the
last one, by throwing
std::invalid_argument, before anything changes. - Check the business rules that this change could break (first: is the
account still open?), and refuse with an
Outcomeif it would. A refusal changes nothing, so the invariants are still true. - Make the change, and only then.
Refusals that are a normal part of using an account (not enough money, over the
limit) return an Outcome. Caller mistakes (a negative amount) throw. That is
the split the errors lesson described.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The only function that changes the balance or the history, so invariant 1// is kept in one place.// amount_cents is already signed here: positive for a deposit, negative for// a withdrawal. `{day, amount_cents}` builds a Transaction in field order.void Account::record(int day, std::int64_t amount_cents) { history_.push_back({day, amount_cents}); // may throw; then nothing changed balance_cents_ += amount_cents;}record is the only function that changes the balance or the history. So
invariant 1, “the balance equals the history’s sum”, is kept in one small
function. If deposits, withdrawals, and some future interest payment each
updated the two fields themselves, one of them would eventually update only
one.
record also orders its two changes carefully. push_back can throw (if memory
runs out). If it does, the balance has not been changed yet, so the invariant
still holds. Changing the balance first would leave a balance with no matching
history entry.
Step 4: a check for tests and debug builds
Section titled “Step 4: a check for tests and debug builds”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Re-checks the invariants from the raw data, trusting nothing that was// stored for speed. One pass over the history adds up the amounts (for 1),// compares each entry's day with the one before it (for 3), and checks each// entry's day against the limit (for 4). Then the last line checks 1, 2,// and the part of 5 that can be seen: a closed account has a zero balance.// ("Records nothing more" is about future calls; deposit and withdraw keep// it by refusing.) Returns false at the first broken rule.bool Account::invariants_hold() const { std::int64_t sum = 0; for (std::size_t i = 0; i < history_.size(); ++i) { sum += history_[i].amount_cents; // `i > 0` first: entry 0 has no entry before it, and `&&` stops // before history_[i - 1] would be read. if (i > 0 && history_[i].day < history_[i - 1].day) { return false; // 3 } // withdrawn_on scans the whole history again, so this loop does // about n * n steps for n transactions: slow, but simple and sure. if (withdrawn_on(history_[i].day) > daily_limit_cents_) { return false; // 4 } } return sum == balance_cents_ // 1 && balance_cents_ >= 0 // 2 && (open_ || balance_cents_ == 0); // 5: open, or else empty}invariants_hold checks every invariant from scratch, without trusting the
stored balance. Tests call it after every operation. Each changing function also
calls it inside assert, so in a debug build a bug that broke an invariant
stops the program at the operation that broke it, not much later where the
wrong number is noticed. In a release build (compiled with NDEBUG), the
asserts disappear and cost nothing.
This check is slow: for every transaction, it scans the whole history for that day’s withdrawals, so its cost grows with the square of the history’s length. Because debug builds run it after every change, building up a history of n transactions costs on the order of _n_³ steps in total. That is acceptable for tests and debug builds of an example, and it is the reason the check is not run in release builds. A real account with years of history would need a cheaper check, or one run only in tests.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Amounts are in cents: 20'000 is $200.00. text() (above main) turns an// Outcome into words. Balance after each line, if it changes: 30'000,// then 15'000, then (day 3) 0. The second withdrawal on day 2 is refused// because the day's total would be 150 + 100 = 250 dollars, over the// limit. On day 3, 200.00 is within the limit, but only 150.00 is left.Account account{"Sam Lee", 20'000}; // daily withdrawal limit: $200.00std::cout << "deposit 300.00 on day 1: " << text(account.deposit(1, 30'000)) << '\n';std::cout << "withdraw 150.00 on day 2: " << text(account.withdraw(2, 15'000)) << '\n';std::cout << "withdraw 100.00 on day 2: " << text(account.withdraw(2, 10'000)) << '\n';std::cout << "withdraw 200.00 on day 3: " << text(account.withdraw(3, 20'000)) << '\n';std::cout << "close: " << text(account.close()) << '\n';std::cout << "withdraw 150.00 on day 3: " << text(account.withdraw(3, 15'000)) << '\n';std::cout << "close: " << text(account.close()) << '\n';// The account is closed now, so the deposit is refused.std::cout << "deposit 10.00 on day 4: " << text(account.deposit(4, 1'000)) << '\n';std::cout << "balance " << account.balance_cents() << " cents, " << account.history().size() << " transactions\n";deposit 300.00 on day 1: donewithdraw 150.00 on day 2: donewithdraw 100.00 on day 2: refused: over the daily limitwithdraw 200.00 on day 3: refused: not enough moneyclose: refused: withdraw the balance firstwithdraw 150.00 on day 3: doneclose: donedeposit 10.00 on day 4: refused: account closedbalance 0 cents, 3 transactionsThe second withdrawal on day 2 would take the day’s total to $250.00, over the $200.00 limit. On day 3, $200.00 is within the limit but more than the $150.00 left, so it is refused for that reason. Closing is refused until the balance is zero. After closing, the deposit is refused, and the history still holds only the three transactions that succeeded.
Getters, setters, and broken rules
Section titled “Getters, setters, and broken rules”Here is a simplified version of the same account, written another way. It compiles without warnings:
Flawed (intentional)Demonstrates a mistake on purpose. Do not copy it; see the corrected version.
// The fields are private, but every one can be changed from outside, with// no checks. The class itself keeps no rule: no "balance >= 0", no// "balance == sum of history", no "closed means empty".class Account {public: [[nodiscard]] std::int64_t balance_cents() const { return balance_cents_; } // FLAW: accepts any number, including a negative one, and does not // touch the history, so balance and history can disagree. void set_balance_cents(std::int64_t cents) { balance_cents_ = cents; }
[[nodiscard]] bool is_open() const { return open_; } // FLAW: closes (or reopens) whatever the balance is. void set_open(bool open) { open_ = open; }
// FLAW: returns a non-const reference (no const anywhere), so a caller // can add, change, or erase history entries directly. [[nodiscard]] std::vector<std::int64_t>& history() { return history_; }
private: std::int64_t balance_cents_ = 0; bool open_ = true; std::vector<std::int64_t> history_;};
// Written carefully: checks the rules, and updates both balance and history.// It works, but only because this author remembered every rule. A refused// withdrawal does nothing and says nothing: the caller cannot tell why.void withdraw(Account& account, std::int64_t cents) { if (account.is_open() && cents > 0 && cents <= account.balance_cents()) { account.set_balance_cents(account.balance_cents() - cents); account.history().push_back(-cents); }}
// Written later, elsewhere, by someone in a hurry.// GOES WRONG: takes 500 cents with no balance check (overdraft allowed) and// no history entry (the history's sum no longer matches the balance).void charge_card_fee(Account& account) { account.set_balance_cents(account.balance_cents() - 500);}
// GOES WRONG: closes without checking that the balance is zero.void close(Account& account) { account.set_open(false);}
int main() { Account account; account.set_balance_cents(300); // a deposit, with no history entry withdraw(account, 200); // balance 100; history {-200}, which sums to -200 charge_card_fee(account); // balance -400: an overdraft close(account); // closed while it owes money // Exit code 1 means "the balance went negative". The compiler accepted // every line: nothing in the class could stop these mistakes. return account.balance_cents() < 0 ? 1 : 0;}Every field is private, yet the rules are not protected at all. A
set_balance_cents that accepts any number is the same as a public
balance_cents_: it gives every caller the power to break the rules, and the
duty to keep them. history() returns a non-const reference, so any caller can
also rewrite the history. The rules now live in the callers:
withdrawis careful: it checks the balance and that the account is open, and updates both fields.charge_card_fee, written later, forgets the overdraft rule. The balance goes to −400. (Run once by hand while writing this page, the program returned 1: the balance was negative.)closeforgets that an account with money, or debt, should not be closed.main’s “deposit” sets the balance directly, so the history no longer matches it.
None of these is a crash. Each is a wrong number that someone finds later, far from the line that caused it.
Private data is not encapsulation by itself. Encapsulation means the class offers operations of the domain, deposit, withdraw, close, which keep the rules, instead of access to its fields. Ask of each member function: could a caller use it to break an invariant? If so, either it should check the rule, or it should not exist.
Testing invariants
Section titled “Testing invariants”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure if// the condition is false. LLD_CHECK_EQ(actual, expected) records a failure// unless the two are equal, and prints both. 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.
// namespace { ... } with no name keeps the helper private to this file.namespace {
// A test account with a daily limit of 10'000 cents and one deposit of// `cents` on day 1. deposit is [[nodiscard]]; static_cast<void> says the// Outcome is ignored on purpose. The account is returned by value (moved// or built in place), so each test gets its own.Account funded(std::int64_t cents) { Account account{"Test", 10'000}; static_cast<void>(account.deposit(1, cents)); return account;}
} // namespace
LLD_TEST(a_new_account_is_open_empty_and_valid) { const Account account{"Test", 10'000}; LLD_CHECK(account.is_open()); LLD_CHECK_EQ(account.balance_cents(), std::int64_t{0}); LLD_CHECK(account.invariants_hold());}
// A limit of 0 would refuse every withdrawal, so no such account is made.LLD_TEST(the_constructor_rejects_a_useless_limit) { LLD_CHECK_THROWS(Account("Test", 0), std::invalid_argument);}
// Invariant 2 at its edge: one cent more than the balance is refused, and// leaves the balance and the one-entry history as they were; exactly the// balance is allowed.LLD_TEST(no_overdraft_and_the_refusal_changes_nothing) { Account account = funded(5'000); LLD_CHECK(account.withdraw(2, 5'001) == Outcome::insufficient_funds); LLD_CHECK_EQ(account.balance_cents(), std::int64_t{5'000}); LLD_CHECK_EQ(account.history().size(), std::size_t{1}); LLD_CHECK(account.withdraw(2, 5'000) == Outcome::done); // exactly all of it LLD_CHECK(account.invariants_hold());}
// Invariant 4 at its edge: 6'000 + 4'000 reaches the 10'000 limit exactly,// so even 1 more cent that day is refused (history stays at 3 entries:// the deposit and two withdrawals). On day 3 the count starts again.LLD_TEST(the_daily_limit_counts_every_withdrawal_that_day) { Account account = funded(50'000); LLD_CHECK(account.withdraw(2, 6'000) == Outcome::done); LLD_CHECK(account.withdraw(2, 4'000) == Outcome::done); // 10'000: at the limit LLD_CHECK(account.withdraw(2, 1) == Outcome::over_daily_limit); LLD_CHECK_EQ(account.balance_cents(), std::int64_t{40'000}); LLD_CHECK_EQ(account.history().size(), std::size_t{3}); LLD_CHECK(account.withdraw(3, 10'000) == Outcome::done); // a new day LLD_CHECK(account.invariants_hold());}
// Caller mistakes throw: a zero amount, a negative amount, and day 0,// which is earlier than the deposit on day 1. Each is wrapped in// static_cast<void> because the function is [[nodiscard]]. The history// still holds only the deposit.//// The last test checks the lifecycle: closing with money is refused and// leaves the account open; after withdrawing everything it closes; then a// deposit and a second close are refused, and the history keeps just the// deposit and the withdrawal.LLD_TEST(bad_arguments_are_rejected_before_anything_changes) { Account account = funded(5'000); LLD_CHECK_THROWS(static_cast<void>(account.deposit(2, 0)), std::invalid_argument); LLD_CHECK_THROWS(static_cast<void>(account.withdraw(2, -10)), std::invalid_argument); LLD_CHECK_THROWS(static_cast<void>(account.deposit(0, 100)), std::invalid_argument); LLD_CHECK_EQ(account.history().size(), std::size_t{1}); LLD_CHECK(account.invariants_hold());}
LLD_TEST(only_an_empty_account_closes_and_then_records_nothing) { Account account = funded(100); LLD_CHECK(account.close() == Outcome::still_has_money); LLD_CHECK(account.is_open()); LLD_CHECK_EQ(account.balance_cents(), std::int64_t{100}); LLD_CHECK(account.withdraw(2, 100) == Outcome::done); LLD_CHECK(account.close() == Outcome::done); LLD_CHECK(account.deposit(3, 100) == Outcome::account_closed); LLD_CHECK(account.close() == Outcome::account_closed); LLD_CHECK_EQ(account.history().size(), std::size_t{2}); LLD_CHECK(account.invariants_hold());}The tests follow the invariants:
- Each rule at its edge. Withdrawing exactly the balance succeeds; one cent more is refused. The day’s withdrawals reach the limit exactly; one cent more is refused; the next day starts again.
- Each refusal changes nothing. After the overdraft, daily-limit, and
bad-argument refusals, the tests check that the balance or the history is
unchanged, and every test ends by checking
invariants_hold(). - The constructor refuses a limit that would make the account useless.
- The lifecycle (open, then closed), which is also an invariant: a closed account is empty and frozen.
What an invariant is not
Section titled “What an invariant is not”- Not a precondition. A precondition is a rule about a function’s arguments, such as “the amount is positive”, which the caller must meet. An invariant is a rule about the object, which the class itself must keep. The account checks its preconditions and throws, but no caller can break its invariants.
- Not necessarily true inside a member function. In the middle of
record, afterpush_backbut before the balance is updated, invariant 1 is briefly false. That is fine, as long as no outside code can see the object at that moment and the function finishes by restoring it, even when something throws. With threads, that “no outside code can see it” needs a lock, which the concurrency lessons cover. - Not a rule across several objects. “Every loan’s copy is not on the shelf” involves two objects. A single class cannot guarantee that alone. It needs a coordinator that owns both changes, like the loan desk in the responsibilities lesson.
Common mistakes
Section titled “Common mistakes”- Invariants that live only in someone’s head. If they are not written down, the next person to change the class cannot keep them.
- A setter for every field, or a non-const reference to internal data.
- A constructor that leaves the object invalid and an
init()function that must be called next. Until then, every invariant is false. - Updating related fields in several places, so that one day one of them is
forgotten. Funnel each change through one function, as
recorddoes. - Changing the state before checking the rule, then trying to undo it when the check fails.
- Testing only successful operations. Refusals must leave the invariants true too.
When a requirement changes
Section titled “When a requirement changes”New requirement: “Premium accounts may go overdrawn by up to $100.00.”
Invariant 2 changes from “balance ≥ 0” to “balance ≥ −overdraft limit”, where
the overdraft limit is 0 for basic accounts. Because the rule was written down
and numbered, the places to change are easy to find: the comment, the
withdrawal check that keeps rule 2, close (can an overdrawn account close?
The bank must decide, and the code must say), and invariants_hold. Callers do
not change at all, because no caller ever checked the balance itself. With the
setter version, every caller that withdraws money would need finding and
changing, and the compiler would not help find them.
Exercise: List the invariants, then protect them
A library’s HoldQueue class keeps, for one title, the members waiting for it,
in the order they asked:
// The members waiting to borrow one title. Every field is public, so any// code holding a HoldQueue can change any of them, in any way.class HoldQueue {public: std::vector<MemberId> waiting; // first in line at the front int max_holds = 20; // the most members that may wait at once // Either holds one MemberId or is empty: a copy is kept for this member. std::optional<MemberId> kept_for;};- Write down the invariants this class should have. Think about duplicates, the
limit, and how
kept_forrelates towaiting. - Rewrite the class so that callers cannot break them. Which operations does it need?
Show the explained answer
-
Invariants (one reasonable set):
- No member appears in
waitingtwice. waiting.size() <= max_holds.max_holdsis at least 1.- A member who has a copy kept for them is no longer waiting: if
kept_forhas a value, it is not inwaiting. - At most one copy is kept at a time (a single
std::optionalalready says so, by its type).
Invariant 4 is a choice. A design could also keep the member at the front of
waitingwhile the copy is kept. Either works, but the class must pick one and write it down. - No member appears in
-
Private data, and domain operations instead of fields:
class HoldQueue {public:// Throws std::invalid_argument if max_holds < 1 (invariant 3).// Starts with nobody waiting and no copy kept.explicit HoldQueue(int max_holds);enum class PlaceResult { placed, already_waiting, copy_already_kept, queue_full };// Refuses duplicates (1), a full queue (2), and the member a copy is// already kept for (4).[[nodiscard]] PlaceResult place(MemberId member);// Returns false if the member was not waiting. Removing a member// cannot break any invariant, so cancel needs no refusals.bool cancel(MemberId member);// A copy came back: keep it for the first member waiting, and remove// them from the queue (4). Returns who it is kept for, or nothing if// nobody is waiting or a copy is already kept (5).std::optional<MemberId> keep_copy_for_next();// The kept copy was collected, or the hold expired.void release_kept_copy() noexcept;// Read-only views: const references, so callers cannot change them.[[nodiscard]] const std::vector<MemberId>& waiting() const noexcept;[[nodiscard]] const std::optional<MemberId>& kept_for() const noexcept;[[nodiscard]] bool invariants_hold() const;private:std::vector<MemberId> waiting_;int max_holds_;std::optional<MemberId> kept_for_;};There is no way to set
waiting_orkept_for_directly. Each operation keeps the invariants it could break:placechecks for duplicates, the limit, and the member already holding the kept copy;keep_copy_for_nextmoves the first member out ofwaiting_and intokept_for_in one step, so invariant 4 is never false outside the class.max_holdshas no setter. If the limit must change later, achange_limit(int)operation must decide what happens to members already beyond the new limit, which is a business question, not a coding one.The tests would call each operation, including the refused ones, and check
invariants_hold()after each.
Summary
Section titled “Summary”- An invariant is a rule about an object that is true whenever outside code can see it. Write each one down, in the class’s header comment.
- The constructor makes the invariants true, or throws. Every public function keeps them true: check arguments, check rules, then change.
- Funnel related changes through one private function, and order changes so that an exception leaves the invariants true.
- Private data with a setter for every field is not encapsulation. Offer domain operations that keep the rules; read-only getters are usually fine.
- Test the edges of each rule, and check the invariants after refused operations too.