Skip to content

Finding classes, data members, and member functions

Difficulty: Intermediate

Key concepts

  • noun filter
  • candidate class
  • data member
  • member function
  • derived data
  • rule placement
  • tell don't ask
  • god class
  • coordinator class
  • A procedure, in seven steps, that takes you from a list of requirements to classes with data members and member functions, and that you can repeat on any problem.
  • How to decide what each noun in a problem statement becomes: a class, a small value type, a data member, an enum value, a function, or nothing.
  • How to decide which class remembers each fact, and which C++ type holds it.
  • How to find member functions by starting from what callers need, not from the data.
  • Where each rule belongs, why “tell, don’t ask” usually gives the better design, and how to spot a class that is too large or too small.

A gym wants a program for its front desk:

Members check in at the front desk. Each member has a membership: either unlimited until a last day, or a pass with a number of visits that also ends on a last day. A member may come in if they are enrolled, are not already inside, the gym is below its capacity, they are not suspended, and their membership allows a visit today. Each visit on a pass uses one visit. Members check out when they leave. Staff can suspend and reinstate a member and renew a membership. The manager wants to see how many people are inside and how many times a member came in during a period.

After the clarification step, the requirements are:

ID Requirement
FR-1 Enrol a member with an ID, a name, and a membership. An ID can be enrolled only once.
FR-2 Check a member in on a given day, or refuse with a reason the desk can show.
FR-3 Refuse if: not enrolled; already inside; gym full; suspended; membership past its last day; no visits left.
FR-4 An admitted visit on a pass uses one visit. A refused check-in changes nothing.
FR-5 Check a member out.
FR-6 Staff can suspend, reinstate, and renew a member.
FR-7 Report how many people are inside, and how many visits a member made between two days.

Out of scope: payments, opening hours, guests, and how days are entered.

The rest of the page turns these seven lines into classes. Each step below has a question to answer and a table to fill in. The tables are the real work. Once they are filled in, the C++ follows from them.

Step Question Output
1 Which nouns does the statement use? a noun list
2 What does each noun become? a noun table: class, value, member, or nothing
3 What kind is each class, and who owns whom? an entity sketch
4 What must each class remember to meet the requirements? a data-member table
5 Which C++ type holds each fact? types in the data-member table
6 What do callers need to ask or tell each class? a member-function table
7 Which class applies each rule? a rule table, then the class outline

Then check the result in two ways: trace one scenario through the outline, and check the size of each class. Steps 2 to 7 are not done once, in order, and finished. Step 6 often shows a fact missing from step 4, and step 7 often moves a member function to another class. Go back and change the earlier table when that happens.

The seven steps, with the final check feeding back into the earlier steps
Text description of the diagram

Seven steps in a row, each feeding the next: 1, nouns; 2, noun table; 3, kinds and sketch; 4, data members; 5, C++ types; 6, member functions; 7, rule placement. Step 7 leads to a final check (a trace and a size check). An arrow from the check back to step 4, labelled “missing fact or misplaced rule”, shows that the check often sends you back.

Diagram source (Mermaid)
flowchart LR
S1["1. Nouns"] --> S2["2. Noun table"]
S2 --> S3["3. Kinds and sketch"]
S3 --> S4["4. Data members"]
S4 --> S5["5. C++ types"]
S5 --> S6["6. Member functions"]
S6 --> S7["7. Rule placement"]
S7 --> C["Check: trace and size"]
C -->|missing fact or misplaced rule| S4

Read the statement and the requirements and write down every noun or noun phrase, once each. Do not judge them yet:

member, front desk, membership, last day, pass, number of visits, gym, capacity, visit, staff, manager, period, ID, name, reason, people inside, day

Seventeen nouns. A beginner’s first design often has close to seventeen classes. MOD-07 showed why that goes wrong: many nouns are facts about other nouns, or people outside the program, or numbers. Step 2 sorts them.

Ask these questions of every noun, in this order:

  1. Is it someone or something outside the program? People who use the program (the front desk, staff, the manager) are callers. They become nothing, or at most a parameter. Outside systems become an interface (MOD-04 and the requirements lessons cover those). Stop here.
  2. Is it the result of an action, or a verb in disguise? “Check-in”, “reason”, “report” usually become a member function or its return type. Stop here.
  3. Does it have rules of its own, or several facts that must change together? Then it is a class. Could it be confused with another number or string of the same type? Then it deserves a small type of its own.
  4. For a class: does it need to be told apart from others that look the same, over time? Then it is an entity with an ID (MOD-03). If two with equal contents are interchangeable, it is a value (MOD-02).
  5. Is it a fact about another noun? Then it is also a data member of the noun it describes. If question 3 made it a class or a type, that is the data member’s type; otherwise the type is a plain int, std::string, and so on.

A noun can get two answers. A membership is a class (question 3) and a fact about a member (question 5), so Member has a data member membership_ of type Membership. A name has no rules, so it is only a data member, of type std::string.

Noun Becomes Why
front desk, staff, manager nothing: callers people who use the program; their actions become member functions
gym class Gym holds the capacity and who is inside, and applies the building’s rules
member class Member (entity) changes over time (suspended, visits used) and must be told apart by ID
ID value type MemberId identifies a member; a separate type so it cannot be mixed up with a day or a count
name data member of Member a fact about a member, with no rules
membership class Membership (value) has its own rules (last day, visits) and two forms that behave alike
pass, unlimited not classes: two ways to create a Membership they differ in data (a visit count or none), not in behaviour
number of visits data member of Membership a fact about a membership; absent for unlimited
last day data member of Membership a fact about a membership
capacity data member of Gym a fact about the building
people inside data member of Gym (the set of IDs); the count is a function the set is a fact; the count is computed from it
visit data member of Member: the days visited only its day is needed; a visit has no rules of its own
day, period Day; a period is two Day parameters here only an alias, using Day = int;, to keep the example small; real code would use std::chrono::sys_days, a distinct type
reason enum class CheckIn the result of an action, one of a fixed set

Seventeen nouns became three classes (Gym, Member, Membership), one small value type (MemberId), a type alias (Day), one enum, and a handful of data members.

Each class from step 2 has a kind (MOD-02), and the kind decides a lot about its C++:

Class Kind What that means here
Member entity has a MemberId that never changes; other facts change through member functions
Membership value copied freely; “renew” replaces it with a new one rather than editing its fields
Gym coordinator the one object the callers talk to; owns the members and applies rules that span them
MemberId value compared and ordered, so it can be a map key

A coordinator (sometimes called a controller or a facade) is the class the callers use. It owns the other objects or knows where they are, and it applies the rules that involve more than one of them. A coordinator should be thin: if it starts reading other objects’ fields and applying their rules, it is turning into the god class described below.

Now sketch who owns whom:

Entity sketch of the gym: the gym owns its members, each member owns one membership, and the gym knows who is inside by ID
Text description of the diagram

Three boxes, each labelled with its kind. A solid arrow goes from Gym (a coordinator) to Member (an entity), labelled “owns 0..*, by MemberId”: the gym holds every enrolled member, found by ID. A dashed arrow, also from Gym to Member, labelled “knows 0..capacity inside, by MemberId”: the gym records which members are inside by their IDs, without a second copy of them. A solid arrow goes from Member to Membership (a value), labelled “owns 1”.

Diagram source (Mermaid)
flowchart LR
Gym["Gym (coordinator)"] -->|"owns 0..*, by MemberId"| Member["Member (entity)"]
Gym -.->|"knows 0..capacity inside, by MemberId"| Member
Member -->|owns 1| Membership["Membership (value)"]

Three decisions are already visible:

  • The gym owns the members. A member exists in this program because the gym enrolled them, and nothing else stores them. One owner means one place to look and no question about lifetime.
  • “Inside” is recorded by ID, not by pointer or by a second copy. An ID cannot dangle if the map changes. A copy would go out of step.
  • A member owns its membership by value. Nobody else needs it, and it is small. “Renew” replaces it.

Go through the requirements one at a time and ask, for each: what must the program still know, later, to meet this requirement? Then put each fact in the class whose rules use it.

Requirement Fact the program must remember Which class Data member
FR-1 the enrolled members, findable by ID Gym members_
FR-1 each member’s ID and name Member id_, name_
FR-1, FR-3 each member’s membership Member membership_
FR-3 the gym’s capacity Gym capacity_
FR-3, FR-5 who is inside now Gym inside_
FR-3, FR-6 whether the member is suspended Member suspended_
FR-3 the membership’s last day Membership last_day_
FR-3, FR-4 visits left on a pass, or that it is unlimited Membership visits_left_
FR-7 the days a member came in Member visit_days_

Three rules decide which class a fact goes in:

  • Put a fact with the rule that reads it. “Is the member suspended?” is part of the member’s admission rule, so suspended_ is in Member. If it were in Gym, as a set of suspended IDs, the member’s rule would need the gym to answer it.
  • Each fact has one home. “Who is inside” could be a bool inside_ in every Member, or a set in Gym. Not both: two copies of one fact go out of step. The set wins here, because the capacity rule needs to count the people inside, and counting a set is one call, while counting flags means visiting every member.
  • Do not store what you can compute. FR-7 asks for “how many people are inside”. That is inside_.size(), so there is no int people_inside_ member to keep in step. “Visits in a period” is counted from visit_days_. Store a computed value only when computing it is too slow, and then make one function responsible for updating it.

Some facts are deliberately not remembered. The gym does not record refused check-ins, because no requirement asks for them. If the manager later wants “how often was the gym full?”, that is a new requirement and a new data member.

A data member’s type is a design decision. It says what values are possible, who owns the data, and what can be absent. Ask these questions about each fact:

Question If yes
Does it have its own rules? a class (here Membership)
Could it be confused with another number or string? a small type (struct MemberId { int value; };)
Can it be absent, with a meaning? std::optional<T>, not a magic value such as -1
Is it one of a fixed set? enum class, not bool pairs or strings
Are there many? a container: which lookups and order do you need?
Is it owned here? a value member or container of values (not a pointer)
Is it owned elsewhere and needed later? an ID (or a reference or pointer, with a lifetime rule; CPP-05)
Must it always hold a valid value? set it in the constructor, or give it a default member initializer

Applied to the gym:

Data member C++ type Why this type
id_ MemberId cannot be passed where a day or a visit count is expected; operator<=> makes it a map key
name_ std::string owned text, only displayed
membership_ Membership owned by value; small; replaced on renewal
suspended_ bool, initialized to false two states with no data; a new member is not suspended
visit_days_ std::vector<Day> appended in order, read in order; the order is the history
last_day_ Day one value; set by the factory function. Day is only an alias for int, so visit_pass(60, 2) with the arguments swapped compiles; a distinct day type (std::chrono::sys_days) would catch it
visits_left_ std::optional<int> empty means unlimited, which is a meaning, not a number
capacity_ int, checked in the constructor must be positive; the constructor throws otherwise, so no Gym has a bad capacity
members_ std::map<MemberId, Member> owns the members; lookup by ID; adding a member never moves the others, so a pointer from find stays valid until that member is removed
inside_ std::set<MemberId> no duplicates, a fast contains, and size() is the count

Find member functions from the outside in. Start with the callers from step 2, and list what each needs to ask or tell. Each need becomes a member function on the class the caller talks to. Then ask what that function needs from the classes below it, and repeat.

The callers talk to Gym:

Need (caller) Requirement Member function Command or query
enrol a member (staff) FR-1 bool enrol(Member member) command
check a member in and show why not (desk) FR-2, FR-3 CheckIn check_in(MemberId id, Day today) command
check a member out (desk) FR-5 bool check_out(MemberId id) command
suspend, reinstate, renew (staff) FR-6 bool suspend(MemberId), reinstate, renew(MemberId, Membership) command
how many are inside (manager) FR-7 int people_inside() const query
a member’s name and visits (desk, manager) FR-7 const Member* find(MemberId id) const query

Gym::check_in needs Member to decide whether the member may come in. Member needs Membership to answer for the membership:

Need (caller) Member function Command or query
may this member come in, and if so record it (Gym) Admission Member::admit(Day today) command
suspend, reinstate, renew (Gym, for staff) void suspend(), reinstate(), renew(Membership) command
visits between two days (manager, through find) int visits_between(Day first, Day last) const query
may this membership be used today (Member) bool Membership::allows_visit(Day today) const query
use one visit (Member) void Membership::use_visit(Day today) command
create an unlimited membership or a pass (staff code) static Membership unlimited_until(Day), visit_pass(int, Day) factory
the ID, to file the member under (Gym::enrol) MemberId id() const query
name and membership, to show them (desk, manager) const std::string& name() const, const Membership& membership() const query
the last day, to tell “expired” from “no visits left” (Member::admit) Day Membership::last_day() const query
visits left, to show them (manager) std::optional<int> Membership::visits_left() const query

The constructors come from FR-1: to enrol a member, someone must create a Member and a Membership.

Notice what is not in these tables: set_suspended(bool), set_visits_left(int), set_capacity(int), a getter for every data member. The getters that are there each have a caller with a reason, written in the first column. Data members came from requirements in step 4. Member functions come from needs. A getter or setter that no caller needs is a way around the class’s rules. suspend() and reinstate() say what staff do; set_suspended(true) only says which field changes.

The details of each signature (why check_in returns an enum and not a bool, why find returns const Member*, when to use [[nodiscard]] and noexcept) are the subject of the next lesson, designing member functions in C++.

Now list every rule in the requirements, and give each one to a class. The guideline is the one from step 4, from the other direction: a rule belongs to the class that holds the data the rule reads. A rule that needs data from several objects, or is about the whole collection, belongs to the coordinator.

Rule (from FR-3, FR-4) Data it reads Owner Where it is applied
the ID must be enrolled members_ Gym check_in, and each staff action
not already inside inside_ Gym check_in
below capacity inside_, capacity_ Gym check_in
not suspended suspended_ Member admit
on or before the last day last_day_ Membership allows_visit (and admit, to give the reason)
a pass has a visit left visits_left_ Membership allows_visit
an admitted visit uses one visit visits_left_ Membership use_visit
an admitted visit is recorded visit_days_ Member admit
a refused check-in changes nothing everything each class every check happens before any change

The last rule is not owned by one class. Each class keeps it by checking everything before it changes anything. That gives an order inside check_in: first the gym’s own rules, which need nothing from the member, then the member’s.

The seven tables, put together:

class Gym

coordinator: the building's rules (enrolled, inside, capacity)

Data members

  • int capacity_; > 0, checked by the constructor
  • std::map<MemberId, Member> members_; owned, by ID
  • std::set<MemberId> inside_; IDs of members now inside

Member functions

  • explicit Gym(int capacity);
  • bool enrol(Member member); false if the ID is taken
  • CheckIn check_in(MemberId id, Day today);
  • bool check_out(MemberId id);
  • bool suspend(MemberId id);
  • bool reinstate(MemberId id);
  • bool renew(MemberId id, Membership membership);
  • int people_inside() const;
  • const Member* find(MemberId id) const; read-only; nullptr if not enrolled

class Member

entity: identity is id_; owns the member's own rules

Data members

  • MemberId id_;
  • std::string name_;
  • Membership membership_;
  • bool suspended_ = false;
  • std::vector<Day> visit_days_; in the order admitted

Member functions

  • Member(MemberId id, std::string name, Membership membership);
  • Admission admit(Day today); checks, then uses a visit and records it
  • void suspend();
  • void reinstate();
  • void renew(Membership membership);
  • int visits_between(Day first, Day last) const;
  • MemberId id() const;
  • const std::string& name() const;
  • const Membership& membership() const;

class Membership

value: what the member has paid for

Data members

  • Day last_day_;
  • std::optional<int> visits_left_; empty: unlimited

Member functions

  • static Membership unlimited_until(Day last_day);
  • static Membership visit_pass(int visits, Day last_day); visits > 0
  • bool allows_visit(Day today) const;
  • void use_visit(Day today); only if allows_visit(today)
  • Day last_day() const;
  • std::optional<int> visits_left() const; empty: unlimited

enum class CheckIn

the reason the desk shows

Values

  • admitted
  • unknown_member
  • already_inside
  • gym_full
  • membership_expired
  • no_visits_left
  • suspended
Class outline of the gym: each data member comes from the step 4 table, each member function from step 6

Membership’s constructor is private, so the only ways to make one are the two named factory functions. Each one creates a valid membership: a pass cannot be created with zero visits. Member also has is_suspended() and visit_days() for display and tests. They are left out of the outline, along with Admission (the member’s four possible answers to admit), because they do not change the design.

Membership owns the two rules about a membership:

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

membership.hpp
// What a member has paid for: valid until a last day, and either unlimited
// or limited to a number of visits. Owns the rule "may this membership be
// used today?", so no other class needs to know how a membership works.
class Membership {
public:
// The two ways to create a Membership. They are "named constructors":
// `static` member functions, called on the class itself, as in
// Membership::unlimited_until(30), with no object needed first. Each name
// says which kind of membership you get, which a plain constructor with
// a magic "-1 visits means unlimited" argument could not.
//
// As many visits as the member likes, up to and including `last_day`.
[[nodiscard]] static Membership unlimited_until(Day last_day);
// A pass for `visits` visits, usable up to and including `last_day`.
// Throws std::invalid_argument unless visits > 0, so a pass with zero
// (or a negative number of) visits can never exist.
[[nodiscard]] static Membership visit_pass(int visits, Day last_day);
// A query: may this membership be used on `today`? True when today is
// not after the last day and, for a pass, at least one visit is left.
// `const` means it changes nothing, so asking twice is safe. `noexcept`
// promises it never throws.
[[nodiscard]] bool allows_visit(Day today) const noexcept;
// A command: uses one visit (none for an unlimited membership).
// Throws std::logic_error unless allows_visit(today): a caller that uses
// a visit without asking first has a bug, and the exception reports it.
void use_visit(Day today);
[[nodiscard]] Day last_day() const noexcept { return last_day_; }
// How many visits are left on a pass; std::nullopt (an empty optional)
// means unlimited, so "no limit" is not a fake number such as -1.
[[nodiscard]] std::optional<int> visits_left() const noexcept { return visits_left_; }
private:
// The real constructor is private, so code outside the class can only
// use the two named functions above, and both of them build a valid
// membership. The part after the colon copies each argument into its
// data member.
Membership(Day last_day, std::optional<int> visits_left) noexcept
: last_day_(last_day), visits_left_(visits_left) {}
Day last_day_; // the last day the membership can be used
std::optional<int> visits_left_; // std::nullopt: unlimited
};

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

membership.cpp
// Two rules, checked in order. First the date: a membership is valid on its
// last day, so only a day after it is refused. Then the visits.
bool Membership::allows_visit(Day today) const noexcept {
if (today > last_day_) return false;
// `!visits_left_` is true when the optional is empty, which means
// unlimited, so the visit is allowed. Otherwise `||` goes on to the
// right side, where *visits_left_ reads the number inside the optional
// (safe, because it is not empty there), and a pass needs at least one.
return !visits_left_ || *visits_left_ > 0;
}
// Ask first, then change: the precondition is checked by calling the query
// above, so the two can never disagree.
void Membership::use_visit(Day today) {
if (!allows_visit(today)) throw std::logic_error("membership does not allow a visit");
// Only a pass holds a number. `if (visits_left_)` is true when the
// optional holds one; `--*visits_left_` then takes one off the number
// inside it. An unlimited membership (empty optional) has nothing to
// count, so it is left alone.
if (visits_left_) --*visits_left_;
}

use_visit checks its precondition and throws if it is broken. A caller that uses a visit without asking first has a bug, and an exception reports the bug instead of letting a pass go to −1 visits.

Member applies the member’s rules and records the visit:

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

member.cpp
// Decides whether this member may come in on `today`, and if so, records the
// visit. Returns the reason as an Admission. It never throws for a refusal:
// being refused is an ordinary outcome, not a bug.
Admission Member::admit(Day today) {
// Check everything first, so that a refusal changes nothing. Each check
// leaves at once with `return`, so a line below it runs only when every
// earlier check passed.
if (suspended_) return Admission::suspended;
// The date is checked here as well as inside allows_visit only to tell
// "expired" apart from "no visits left": allows_visit just says no.
if (today > membership_.last_day()) return Admission::membership_expired;
// The date is fine, so a "no" from allows_visit must mean the pass is
// used up.
if (!membership_.allows_visit(today)) return Admission::no_visits_left;
// Every check passed. use_visit cannot throw here, because its own
// precondition, allows_visit(today), was just checked.
membership_.use_visit(today);
// Record the day at the end of the list. Callers check members in in
// date order (nothing here enforces it), so the list reads oldest first.
visit_days_.push_back(today);
return Admission::admitted;
}

admit asks for the last day itself, before calling allows_visit, only to give the desk the right reason. allows_visit alone would say “no” without saying whether the membership expired or ran out of visits. That is a small piece of “ask, then decide” inside the final design: the expiry rule is now read in two places. A cleaner version would have Membership return the reason itself (an enum instead of a bool). The example keeps the bool because it is simpler to read, and the cost is one comparison.

Gym applies its own rules, then tells the member to admit itself:

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

gym.cpp
// Lets a member in, or returns the reason they are refused. Order: find the
// member, apply the gym's two rules, then tell the member to admit itself.
CheckIn Gym::check_in(MemberId id, Day today) {
// A pointer into members_, or nullptr if nobody has this ID.
Member* member = find_enrolled(id);
if (member == nullptr) return CheckIn::unknown_member;
// The gym's own rules first: they need nothing from the member. Checking
// them before admit() matters: admit() uses a visit, so a member must
// not be asked until the gym knows it can take them.
if (inside_.contains(id)) return CheckIn::already_inside;
if (people_inside() >= capacity_) return CheckIn::gym_full;
// Then tell the member to admit itself. Nothing has changed yet, so a
// refusal leaves everything as it was.
// `member->admit(today)` calls admit on the Member the pointer points
// at: `->` is `.` for a pointer. The Member applies its own rules.
const Admission admission = member->admit(today);
// Only an admitted member is counted inside. Whatever the answer, it is
// turned from the member's Admission into the desk's CheckIn by
// from_admission, a small switch earlier in this file.
// If insert() ran out of memory, the visit would be used but the member
// not marked inside; the example accepts that rare case.
if (admission == Admission::admitted) inside_.insert(id);
return from_admission(admission);
}

check_in does not know how a membership works or what makes a member suspended. If a membership rule changes, Gym does not, unless the change needs a new reason to show the desk (see “When a requirement changes”).

The design above was not the first one most people would write. Here are the two usual earlier versions. Both compile, and both give the same answers as the final design in the scenarios the tests check. The problems are in what it costs to change them.

This idea has a name: tell, don’t ask. Instead of asking an object for its data and deciding for it, tell it what you want and let it decide. It is a guideline, not a law. Queries are fine when the caller needs the answer for itself: the desk asks for a member’s name to print it, and nothing is decided with it. The warning sign is a caller that asks for data and then changes the same object based on the answer, as getter_style::Gym::check_in does with set_visits_left.

Trace a check-in through the outline, one call at a time. Each step must be a member function in the outline, called on an object the caller can reach. In the program’s run below, Ana is already inside when Ben arrives on day 5, and Ben has a two-visit pass that ends on day 60:

  1. The desk calls gym.check_in({2}, 5).
  2. Gym looks up {2} in members_ → Ben’s Member.
  3. Gym checks inside_.contains({2}) → false.
  4. Gym checks people_inside() (1) against capacity_ (2) → room.
  5. Gym calls ben.admit(5).
  6. Member checks suspended_ → false.
  7. Member checks 5 against membership_.last_day() (60) → not expired.
  8. Member calls membership_.allows_visit(5) → true (2 left).
  9. Member calls membership_.use_visit(5) → 1 left.
  10. Member appends 5 to visit_days_ → returns Admission::admitted.
  11. Gym inserts {2} into inside_ → returns CheckIn::admitted.

Every step has a receiver that holds the data it uses, and nothing changes before step 9, when every check has passed. If a step had needed data that its receiver does not have (for example, Member needing to know how many people are inside), the rule would be in the wrong class.

The whole program, which runs a day of check-ins:

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

main.cpp
Gym gym(2); // at most two people inside at once
// `{1}` builds a MemberId whose value is 1. Each Member is built right in
// the call, then moved into the gym's map by enrol. Ana: unlimited until day 30. Ben: a
// two-visit pass until day 60. Cy: unlimited until day 10. enrol's bool
// result is not needed here, because the three IDs are all different.
gym.enrol(Member({1}, "Ana", Membership::unlimited_until(30)));
gym.enrol(Member({2}, "Ben", Membership::visit_pass(2, 60)));
gym.enrol(Member({3}, "Cy", Membership::unlimited_until(10)));
// A small helper (a lambda) for "this person arrives at the desk on this
// day": it tries to check them in and prints the result. [&] lets it use
// `gym` from the enclosing code by reference, not as a copy.
auto arrive = [&](MemberId id, Day today) {
const Member* member = gym.find(id);
// Use the member's name if they are enrolled; otherwise show "#"
// and the ID number, because there is no name to show.
const std::string name = member != nullptr ? member->name() : "#" + std::to_string(id.value);
std::cout << "day " << today << ", " << name << ": " << to_string(gym.check_in(id, today))
<< '\n';
};
// Day 5: Ana comes in, then tries again; Ben comes in (the gym is now
// full); Cy is refused, then admitted once Ana leaves.
arrive({1}, 5);
arrive({1}, 5);
arrive({2}, 5);
arrive({3}, 5);
gym.check_out({1});
arrive({3}, 5);
gym.check_out({2});
gym.check_out({3});
// Day 12: Cy's membership ended on day 10. Ben uses the second and last
// visit on the pass, leaves, and is refused on coming back. Ana is
// suspended first, so Ana is refused. Nobody has ID 9.
arrive({3}, 12);
arrive({2}, 12);
gym.check_out({2});
arrive({2}, 12);
gym.suspend({1});
arrive({1}, 12);
arrive({9}, 12);
std::cout << "inside now: " << gym.people_inside() << '\n';
// find returns a pointer; `*` turns it into the Member itself, and the
// reference `ben` names it without copying. Safe only because ID 2 is
// certainly enrolled: `*` on a nullptr would be undefined behaviour.
const Member& ben = *gym.find({2});
// value_or(-1) reads the number in the optional, or -1 if it is empty
// (unlimited). Ben has a pass, so it prints the real count, 0.
std::cout << "Ben: " << ben.visits_between(1, 31) << " visits this month, "
<< ben.membership().visits_left().value_or(-1) << " left\n";
Expected output
day 5, Ana: admitted
day 5, Ana: refused: already inside
day 5, Ben: admitted
day 5, Cy: refused: the gym is full
day 5, Cy: admitted
day 12, Cy: refused: membership expired
day 12, Ben: admitted
day 12, Ben: refused: no visits left
day 12, Ana: refused: suspended
day 12, #9: refused: unknown member
inside now: 0
Ben: 2 visits this month, 0 left

Ana’s second arrival on day 5 is refused because Ana is already inside. Cy is refused while the gym is full, then admitted after Ana leaves. On day 12, Cy’s membership has expired, Ben uses the second and last visit on the pass and is refused after checking out and coming back, and Ana has been suspended. ID 9 was never enrolled. Everyone who came in has checked out by the end, so nobody is inside, and Ben’s history shows the two visits.

The tests check each class alone and then through the gym:

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

test_gym_check_in.cpp
// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure if
// the condition is false. LLD_CHECK_EQ(actual, expected) does the same for
// `actual == expected`, and prints both values when they differ.
// 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. The test names say what each test proves.
//
// Membership alone, with no Member or Gym: a two-visit pass allows two
// visits, then says no, and use_visit throws if asked anyway. A pass with
// zero visits cannot even be created.
LLD_TEST(a_visit_pass_uses_one_visit_per_admission_and_then_refuses) {
Membership pass = Membership::visit_pass(2, 60);
LLD_CHECK(pass.allows_visit(1));
pass.use_visit(1);
pass.use_visit(2);
LLD_CHECK(!pass.allows_visit(3));
LLD_CHECK_THROWS(pass.use_visit(3), std::logic_error);
LLD_CHECK_THROWS(Membership::visit_pass(0, 60), std::invalid_argument);
}
// The boundary of the date rule: day 30 is allowed, day 31 is not.
LLD_TEST(a_membership_is_valid_on_its_last_day_but_not_after) {
const Membership monthly = Membership::unlimited_until(30);
LLD_CHECK(monthly.allows_visit(30));
LLD_CHECK(!monthly.allows_visit(31));
}
// Member alone: a suspended member is refused, and the refusal used no
// visit (still 1 left) and recorded no visit day.
LLD_TEST(a_refused_admission_changes_nothing) {
Member ben({2}, "Ben", Membership::visit_pass(1, 60));
ben.suspend();
LLD_CHECK(ben.admit(5) == Admission::suspended);
const std::optional<int> left = ben.membership().visits_left();
LLD_CHECK(left == 1); // an optional equals 1 only if it holds 1
LLD_CHECK(ben.visit_days().empty());
}
// Through the gym: gym_with (a helper above this snippet) builds a gym with
// the given capacity, Ana (ID 1) with the given membership, and Ben (ID 2)
// with an unlimited membership until day 100. One check-in counts one person
// inside and one visit in Ana's history.
LLD_TEST(check_in_admits_records_the_visit_and_counts_the_person_inside) {
Gym gym = gym_with(5, Membership::unlimited_until(30));
LLD_CHECK(gym.check_in({1}, 4) == CheckIn::admitted);
LLD_CHECK_EQ(gym.people_inside(), 1);
const int visits = gym.find({1})->visits_between(1, 31);
LLD_CHECK_EQ(visits, 1);
}
// The order of the checks: with capacity 1 and Ben inside, Ana is refused
// as "full" before the member rules run, so Ana's pass keeps all 3 visits.
LLD_TEST(the_gym_checks_its_own_rules_before_asking_the_member) {
Gym gym = gym_with(1, Membership::visit_pass(3, 60));
LLD_CHECK(gym.check_in({2}, 4) == CheckIn::admitted);
// Full: Ana is refused, and her pass is not touched.
LLD_CHECK(gym.check_in({1}, 4) == CheckIn::gym_full);
const std::optional<int> left = gym.find({1})->membership().visits_left();
LLD_CHECK(left == 3);
LLD_CHECK(gym.check_in({2}, 4) == CheckIn::already_inside);
}
// Leaving frees the one place, so Ana gets in. Checking out twice returns
// false the second time, because Ben is no longer inside.
LLD_TEST(check_out_frees_a_place) {
Gym gym = gym_with(1, Membership::unlimited_until(30));
LLD_CHECK(gym.check_in({2}, 4) == CheckIn::admitted);
LLD_CHECK(gym.check_out({2}));
LLD_CHECK(!gym.check_out({2}));
LLD_CHECK(gym.check_in({1}, 4) == CheckIn::admitted);
}
// Each member-side reason reaches the desk as a CheckIn: expired, then
// (after renewing and suspending) suspended, then admitted once reinstated.
// The staff commands return false for an ID that is not enrolled.
LLD_TEST(member_rules_are_reported_through_the_gym) {
Gym gym = gym_with(5, Membership::unlimited_until(10));
LLD_CHECK(gym.check_in({1}, 11) == CheckIn::membership_expired);
LLD_CHECK(gym.renew({1}, Membership::unlimited_until(40)));
LLD_CHECK(gym.suspend({1}));
LLD_CHECK(gym.check_in({1}, 11) == CheckIn::suspended);
LLD_CHECK(gym.reinstate({1}));
LLD_CHECK(gym.check_in({1}, 11) == CheckIn::admitted);
LLD_CHECK(gym.check_in({7}, 11) == CheckIn::unknown_member);
LLD_CHECK(!gym.suspend({7}));
}
// A second enrol with the same ID is refused and does not replace Ana.
// Gym(0) throws, so a gym with no room cannot exist.
LLD_TEST(an_id_can_be_enrolled_only_once) {
Gym gym(3);
LLD_CHECK(gym.enrol(Member({1}, "Ana", Membership::unlimited_until(30))));
LLD_CHECK(!gym.enrol(Member({1}, "Someone else", Membership::unlimited_until(90))));
LLD_CHECK_EQ(gym.find({1})->name(), std::string("Ana"));
LLD_CHECK_THROWS(Gym(0), std::invalid_argument);
}
LLD_TEST(the_flawed_version_gives_the_same_answers) {
// The problem with ask_style::Gym is not that it is wrong today.
// Same scenario as the next test: capacity 1, Ana unlimited (-1) until
// day 30, Ben a one-visit pass until day 60.
ask_style::Gym flawed(1);
flawed.enrol(1, "Ana", 30, -1);
flawed.enrol(2, "Ben", 60, 1);
LLD_CHECK_EQ(flawed.check_in(2, 5), std::string("admitted"));
LLD_CHECK_EQ(flawed.check_in(1, 5), std::string("gym full"));
flawed.check_out(2);
LLD_CHECK_EQ(flawed.check_in(2, 6), std::string("no visits left"));
LLD_CHECK_EQ(flawed.check_in(1, 31), std::string("membership expired"));
}
// The getter version gives the same answers too: its flaw, like the first
// one's, is in what it costs to change, which a test cannot show.
LLD_TEST(the_getter_version_gives_the_same_answers) {
getter_style::Gym better(1);
better.enrol(getter_style::Member({1}, "Ana", 30, std::nullopt));
better.enrol(getter_style::Member({2}, "Ben", 60, 1));
LLD_CHECK(better.check_in({2}, 5) == CheckIn::admitted);
LLD_CHECK(better.check_in({1}, 5) == CheckIn::gym_full);
better.check_out({2});
LLD_CHECK(better.check_in({2}, 6) == CheckIn::no_visits_left);
LLD_CHECK(better.check_in({1}, 31) == CheckIn::membership_expired);
}

the_gym_checks_its_own_rules_before_asking_the_member checks the order from step 7: when the gym is full, Ana is refused, and Ana’s pass still has three visits. If check_in asked the member first, admit would use a visit that the gym then refuses.

There are two ways to get the size wrong, and both are common.

Too large: a god class. A god class holds most of the data and applies most of the rules, while the other classes (if any) are bags of fields. ask_style::Gym is one. Signs:

  • several containers keyed by the same ID (parallel maps);
  • data members that are used by only some member functions, in groups;
  • a name such as Manager, System, or Engine that does not say what it is responsible for;
  • every new requirement edits it.

The fix is the procedure above: each group of facts that is used together becomes a class, and its rules move with it.

Too small: micro-classes. The opposite mistake splits a design into classes that each hold one field or do one step:

  • Capacity, SuspensionStatus, and VisitCounter, each wrapping one value with a getter;
  • CheckInValidator, CheckInProcessor, and CheckInRecorder, which together do what Gym::check_in does, with data passed between them.

Each class is easy to read, but a reader must open six files to follow one check-in, and the rules are no longer next to the data. Ask of each class: does it protect a rule or an invariant, or hide a decision that may change? Membership does both. MemberId holds one int, but it earns its place: it stops a member ID being passed as a day. SuspensionStatus would do neither.

Sign Too large Too small
number of data members many, in unrelated groups one, with a getter and a setter
where the rules are all in this class in some other class that reads this one
name Manager, System Validator, Helper, Info, Data
what a new requirement changes always this class many small classes at once
  • Do not run all seven tables for a small program. A command-line tool with one class and no rules is done after step 4. The procedure pays when there are rules to place.
  • Do not turn a plain record into a class with rules it does not have. A row in a report (a name and a count) is a struct with public members. There is nothing to protect, so getters add nothing.
  • Do not split a class only to make it shorter. Split it when a group of its data members and the rules that use them can stand alone.
  • Do not insist on “tell, don’t ask” for display. A view that prints a member asks for the name; that is what queries are for.

Putting rules with their data spreads one use case across several classes: to understand a check-in, you read Gym, Member, and Membership. The god class keeps it in one function. For three rules that may be the better trade, and that is why the flawed versions are not wrong today. The distributed design pays back when rules change or grow, because each change lands in one small class with its own tests. A trace (Check 1) is the way to see the whole use case again when you need it.

  • One class per noun. Seventeen nouns are not seventeen classes. Most are facts, callers, or results.
  • A getter and a setter for every data member. Members come from requirements; functions come from callers’ needs.
  • Storing the same fact twice, such as a bool inside_ on each member as well as a count in the gym.
  • Storing a computed value (people_inside_) when it can be computed.
  • Magic values (-1 for “unlimited”) instead of std::optional or an enum.
  • Inheritance for a difference in data. Two kinds of membership that behave the same are one class with an optional member.
  • Checking after changing. A refused request that has already used a visit breaks FR-4.

The gym adds weekday memberships: valid only Monday to Friday, until a last day. What changes?

  • Membership gains the rule. It needs a data member that records which days are allowed, for example bool weekdays_only_ = false;, a factory function weekdays_until(Day last_day), and a check in allows_visit. With Day as a plain int, it also needs a way to find the day of the week, which is a good reason to move to std::chrono::sys_days now.
  • Member::admit needs a new reason, so Admission and CheckIn gain not_valid_today, to_string gains a line, and admit checks for it.
  • Gym does not change, apart from from_admission mapping the new value.

In ask_style::Gym, the same change adds a sixth parallel map and another line in the middle of check_in. That is the cost the great solution avoids.

If the gym later adds memberships that are valid only at certain branches, only at certain hours, and for certain classes, allows_visit grows a set of unrelated rules, and a membership’s behaviour now differs by kind. That is the point where a small interface for “the membership’s rule”, with one class per kind, starts to earn its place. The principles and patterns sections return to this.

Exercise: Run the procedure on library reservations

A library wants reservations:

A member can reserve a title when no copy of it is on the shelf. When a copy of the title is returned, it is held for the member whose reservation is oldest, for three days. A member may have at most five reservations at a time. A member can cancel a reservation. Staff can see the queue for a title. The catalog (which titles exist and which copies are on the shelf) already exists as a class, Catalog.

  1. Fill in the noun table (step 2).
  2. Fill in the data-member table with C++ types (steps 4 and 5).
  3. List the member functions the callers need (step 6), and say which class applies each rule (step 7).
  4. Write a class outline.
  5. Name one question you would ask the library before writing code.
Show the explained answer

This is one reasonable answer; others are possible.

1. Noun table.

Noun Becomes
member, staff callers; a member is identified by MemberId
title an ID, TitleId: the catalog owns titles
copy an ID, CopyId
shelf nothing new: Catalog already knows what is on the shelf
reservation nothing more than a MemberId in a title’s queue: the queue’s order already says which is oldest
queue (for a title) class ReservationQueue: it has rules (oldest first, one per member)
hold value struct Hold { MemberId member; CopyId copy; Day until; }
three days, five constants, static constexpr int
the library’s reservations coordinator class ReservationDesk

2. Data members.

Fact Class C++ type
waiting members, oldest reservation first ReservationQueue std::deque<MemberId> waiting_ (add at the back, take from the front)
the copy held for a member, if any ReservationQueue std::optional<Hold> hold_ (assumes one held copy per title at a time; see question 5)
one queue per title ReservationDesk std::map<TitleId, ReservationQueue> queues_
which copies are on the shelf Catalog (exists) const Catalog& catalog_ in ReservationDesk: not owned; must outlive the desk

A member whose copy is being held still has the reservation: contains, cancel, and the count of a member’s reservations all include the hold.

“How many reservations does a member have?” is not stored. It is counted across the queues (the queues for which contains(member) is true) when a member reserves. That is slower, but there is no second copy to keep in step. If it is too slow, a std::map<MemberId, int> updated only in reserve and cancel is the fix.

3. Member functions and rules.

Need (caller) Member function Rule applied, and where
reserve (member) ReserveResult ReservationDesk::reserve(MemberId, TitleId) no copy on the shelf (desk asks Catalog); at most five (desk, across queues); not twice for one title (ReservationQueue::contains)
cancel (member) bool ReservationDesk::cancel(MemberId, TitleId) removes from the queue (ReservationQueue::cancel)
a copy came back (the return desk) std::optional<Hold> ReservationDesk::copy_returned(TitleId, CopyId, Day) oldest first, held three days (ReservationQueue::offer)
see the queue (staff) std::vector<MemberId> ReservationDesk::queue_for(TitleId) const none

The five-reservation limit is a rule about one member across many queues, so no single queue can apply it: it belongs to the coordinator. “Oldest first” and “three days” are about one queue, so ReservationQueue applies them.

4. Class outline.

class ReservationDesk

coordinator: rules across titles and the catalog

Data members

  • const Catalog& catalog_; not owned; must outlive the desk
  • std::map<TitleId, ReservationQueue> queues_;
  • static constexpr int max_reservations = 5;

Member functions

  • ReserveResult reserve(MemberId member, TitleId title);
  • bool cancel(MemberId member, TitleId title);
  • std::optional<Hold> copy_returned(TitleId title, CopyId copy, Day today);
  • std::vector<MemberId> queue_for(TitleId title) const;

class ReservationQueue

the waiting list for one title: oldest first

Data members

  • std::deque<MemberId> waiting_;
  • std::optional<Hold> hold_;
  • static constexpr int hold_days = 3;

Member functions

  • bool contains(MemberId member) const; waiting or holding
  • void add(MemberId member); only if !contains(member)
  • bool cancel(MemberId member); waiting or holding
  • std::optional<Hold> offer(CopyId copy, Day today); oldest becomes the hold
  • std::vector<MemberId> members_in_order() const;

struct Hold

value

Data members

  • MemberId member;
  • CopyId copy;
  • Day until; today + hold_days

enum class ReserveResult

why a reservation was refused, or that it worked

Values

  • reserved
  • copy_on_shelf
  • limit_reached
  • already_reserved
One answer: a coordinator for the rules across titles, and a queue per title for the rules within one

5. A question to ask. What happens when a hold runs out? Does the copy go to the next member in the queue, or back on the shelf? The statement does not say, and the answer changes ReservationQueue (it would need an expire_hold(Day today) command). Also worth asking: can two copies of one title be held at once for two members? The outline above assumes not.

  • Run the procedure: list the nouns; sort each into a class, a value, a data member, an enum, a function, or nothing; give each class a kind and an owner; list what each class must remember, with C++ types; list what callers need; place each rule with its data; then trace a scenario and check each class’s size.
  • Data members come from requirements: what must the program still know later? Each fact has one home, and computed values are not stored.
  • A data member’s type is a decision: a small type for an ID, std::optional for “may be absent”, an enum class for a fixed set, a value for ownership, an ID for things owned elsewhere.
  • Member functions come from callers’ needs, from the outside in. A getter or setter that nobody needs is a way around the rules.
  • Put a rule in the class that holds the data it reads; rules about the whole collection go to the coordinator. Tell an object what to do rather than asking for its data and deciding for it.
  • A god class and a swarm of micro-classes are both wrong sizes. A class earns its place by protecting a rule or hiding a decision.