Skip to content

Case study: parking lot

Difficulty: Intermediate

Key concepts

  • spot allocation
  • vehicle and spot compatibility
  • fee rules
  • strategy pattern
  • ticket lifecycle
  • shared ownership of an immutable object
  • test doubles
  • over-modeling
  • requirement changes
  • How to turn “design a parking lot” into a short, numbered list of requirements by asking a few questions that change the design.
  • Why a vehicle and a spot size are enums here, not class hierarchies, and why there is no Floor, Gate, or Vehicle class.
  • How to decide which class owns each rule: the car park chooses spots, the ticket decides what is due and whether it may leave, and a fee rule only computes a price.
  • When the Strategy pattern is justified, and why each ticket shares the fee rule that was in force when it was issued, through std::shared_ptr<const FeeRule>.
  • How to keep an outside service (the card provider) behind a small interface so that every path, including a declined card, can be tested.
  • How the design absorbs two later changes, floors and electric-vehicle chargers, and what had to move.
  • How to present the design in 45 minutes, and what is usually expected at junior, mid-level, and senior level.

This page follows the layout described in How to approach a case study. If this is your first study, read that page first; it explains why each section is here.

“Design a parking lot.”

That is all. In an interview this is deliberately vague: the interviewer wants to see what you ask before you design anything. In a real project the same sentence might arrive from a client who runs one car park and wants software for its gates and pay stations.

Each question below is worth asking because its answer changes the design. The answers are examples; a different client could answer differently, and the design would change with them. See Clarifying questions for how to choose such questions.

Question Example answer What it changes in the design
What kinds of vehicles, and what sizes of spot? Motorcycles, cars, and vans. Small, regular, and large spots. Two small enums and one table of which vehicle fits which spot (FR-1).
May a vehicle use a bigger spot than it needs? Yes, but only when the right size is full. Large spots are scarce; keep them for vans. The order in which spots are tried (FR-2).
Does the driver choose the spot, or does the system? The system. The entrance prints the spot number on the ticket. The car park needs a function that chooses a spot.
How is the fee worked out? A price per started hour, by vehicle kind. On event days a flat price per stay instead. Two fee rules, and a way to switch between them (FR-5).
If the prices change while a car is parked, which price applies? The price shown at entry. We print it on the ticket. Each ticket remembers its own rule (FR-4). This answer, more than any other, shapes the design.
How do drivers pay? By card at a pay station before going to the exit. No cash. A card provider outside the system, behind an interface (FR-6).
How long may a driver take to leave after paying? 15 minutes. After that they pay the difference. An exit window on each ticket (FR-7).
How many spots, gates, and floors? About 2,000 spots on one level, two entrances, one exit, one server. A second level is planned. Simple linear searches are enough; the floors become a later change.
What about lost tickets, reservations, monthly passes, refunds? Not now. Out of scope, listed so that nobody assumes they are covered.

Notice what was not asked: nothing about colours of cars, licence plates, or the driver’s name. None of those change what the system does with the answers above, so none of them become part of the design.

In scope

  • Admitting motorcycles, cars, and vans, and choosing a spot for each. (confirmed)
  • A board at the entrance with the number of free spots of each size. (confirmed)
  • Tickets, the hourly and flat fee rules, switching rules, card payment, and the exit gate. (confirmed)

Out of scope

  • Lost tickets, reservations, monthly passes, cash, refunds, and receipts. (confirmed)
  • Licence-plate cameras. (confirmed)
  • The gate, board, and pay-station hardware. The design gives them functions to call; it does not drive motors or screens. (assumed)
  • Saving tickets to disk. Everything is in memory; see Concurrency and persistence. (assumed)

Assumptions

  • Money is a whole number of cents. (confirmed: the client’s prices are all in cents)
  • The server handles one request at a time, so the core needs no locks. (assumed; revisited under Concurrency and persistence)
  • More fee rules will come (a daily cap was mentioned as “maybe next year”). (assumed)
  • Times are in UTC, passed in by the caller, so a change to or from summer time cannot make a stay look shorter or longer. (assumed)
  • A ticket number is never reused while the program runs. (assumed)

An assumption is a decision you made without an answer. Writing it down lets someone correct it; see Assumptions.

Functional requirements

  • FR-1 The car park admits motorcycles, cars, and vans. A vehicle parks only in a spot it fits: a motorcycle in any spot, a car in a regular or large spot, a van in a large spot only.
  • FR-2 On entry the system chooses the spot: the smallest size that fits, then the lowest spot number. If no spot that fits is free, the vehicle is refused.
  • FR-3 The entrance board shows the number of free spots of each size.
  • FR-4 Each entry gets a ticket with a number, the spot, the entry time, and the fee rule in force at entry. The rule on a ticket never changes.
  • FR-5 There are two fee rules. Hourly: a price per started hour, by vehicle kind, with a minimum of one hour. Flat: one price per stay, by vehicle kind. The operator can switch rules at any time.
  • FR-6 A driver pays by card at a pay station. The amount is the fee so far minus what the ticket has already paid. A declined card changes nothing.
  • FR-7 The exit gate opens for a ticket when nothing is due: within 15 minutes of paying, or when the fee so far is fully paid. A ticket that has exited cannot open the gate again.

Non-functional requirements

  • NFR-1 Up to about 2,000 spots and a few thousand tickets a day, held in memory. Each operation should answer at once for a driver at a gate. (Not measured; entry and the board scan the spots, and payment and exit find the ticket by its number.)
  • NFR-2 Money is an exact whole number of cents, stored as a 64-bit integer. No floating point.
  • NFR-3 Every rule can be tested without gates, boards, a card provider, or a real clock.
  • NFR-4 Adding a fee rule does not change the car park or the ticket. (from the assumption that more rules will come)

Each use case has acceptance criteria written as checks a test can make. The test names later on the page start with these IDs. See Use cases.

UC-1 Enter. A driver arrives at an entrance with a vehicle.

  • AC-1.1 The driver gets a ticket with a new number and the chosen spot.
  • AC-1.2 The spot is the smallest free size that fits, and among those the lowest number.
  • AC-1.3 If no spot that fits is free, the vehicle is refused and nothing changes, even if spots of other sizes are free. No ticket number is used up.
  • AC-1.4 The board’s counts go down when a vehicle parks and up when it leaves.

UC-2 Pay. A driver puts a ticket and a card into a pay station.

  • AC-2.1 Hourly: each started hour costs the vehicle’s price, with a minimum of one hour. Exactly one hour is one hour; one second more is two.
  • AC-2.2 Flat: one price however long the stay.
  • AC-2.3 A declined card changes nothing: the amount due and the exit are as before.
  • AC-2.4 Paying again within 15 minutes of paying is refused with “nothing due”, and the card is not charged.
  • AC-2.5 After the 15 minutes, only the difference is charged.
  • AC-2.6 An unknown ticket or a ticket that has exited is refused.

UC-3 Exit. A driver puts a ticket into the exit gate.

  • AC-3.1 Within 15 minutes of paying (15 minutes exactly still counts), the gate opens and the spot becomes free.
  • AC-3.2 An unpaid ticket keeps the gate shut, and the driver is told the amount due.
  • AC-3.3 After the 15 minutes, the gate opens only if nothing more is due; otherwise the driver is told the difference.
  • AC-3.4 An unknown ticket or a ticket that has exited is refused.

UC-4 Change pricing. The operator switches the fee rule.

  • AC-4.1 Vehicles that enter after the change pay by the new rule.
  • AC-4.2 Tickets issued before the change keep the rule they were issued with.

An invariant is a statement that is true whenever no member function is running. Each one below says which class keeps it true. See Invariants.

  • INV-1 A spot holds at most one ticket. A ticket that has not exited is held by exactly the spot it names; a ticket that has exited is held by no spot. (ParkingLot)
  • INV-2 For each size, the free count on the board equals the number of spots of that size that hold no ticket. (ParkingLot: the count is computed from the spots, so it cannot disagree with them)
  • INV-3 A ticket’s spot fits its vehicle. (ParkingLot, when it chooses the spot)
  • INV-4 What a ticket has paid never exceeds its fee so far, so the amount due is never negative. (Ticket checks it; a fee rule that keeps its contract, a longer stay never costs less, makes it hold)

Start with the nouns in the requirements and the answers: car park, spot, size, vehicle, kind, ticket, fee, fee rule, price, pay station, card, card provider, gate, board, driver, operator. Then filter them (the first step in the class-design steps on How to approach a case study):

  • Car park runs every use case and owns the spots and tickets. It becomes the class ParkingLot, the orchestrator.
  • Ticket holds state that changes (paid, exited) and enforces rules (what is due, whether it may leave). It becomes the class Ticket.
  • Fee rule is a rule that varies and will grow (FR-5, NFR-4). It becomes an interface, FeeRule, with HourlyRule and FlatRule.
  • Card provider is outside the system. It becomes an interface, Payments, that the car park is given.
  • Spot holds one changing fact, which ticket is parked there. That is not enough behaviour for a public class: it becomes a small private struct inside ParkingLot.
  • Vehicle is a noun the system never stores anything about except its kind. No plate, no owner, no behaviour. It becomes the enum VehicleKind, and the size becomes the enum SpotSize.
  • Price, fee, and card are information. Prices become a small struct, Prices; a fee is a number of cents; a card is a token string handed to the provider.
  • Pay station, gate, board, driver, and operator are outside. They are the callers of ParkingLot’s functions, so they are dropped from the design.
Entity sketch of the car park (step 2). Solid arrows: owns, shares, or is a. Dashed arrows: knows by ID, or uses without owning
Text description of the diagram

Seven boxes. Solid arrows mean “owns”, “shares ownership”, or “is a”; dashed arrows mean “knows by ID” or “uses without owning”. ParkingLot owns one or more Spot objects and zero or more Ticket objects. ParkingLot shares the current FeeRule, and each Ticket shares the FeeRule that was in force when it was issued. A Spot knows its Ticket by ID, and a Ticket knows its Spot by ID. ParkingLot uses Payments but does not own it. HourlyRule is a FeeRule, and FlatRule is a FeeRule.

Diagram source (Mermaid)
flowchart LR
Lot[ParkingLot] -->|"owns 1..* spots"| Spot
Lot -->|"owns 0..* tickets"| Ticket
Lot -->|shares the current rule| FeeRule
Ticket -->|shares the rule in force at entry| FeeRule
Spot -.->|knows its ticket, by ID| Ticket
Ticket -.->|knows its spot, by ID| Spot
Lot -.->|uses, not owned| Payments
HourlyRule -->|is a| FeeRule
FlatRule -->|is a| FeeRule

ParkingLot orchestrates every workflow. Spots and tickets belong to it. The fee rules are shared, because a ticket must keep using its rule even after the car park has moved on to another one. Payments belongs to whoever builds the car park (in the demo, main), as described in Composition roots.

The design below is step 2 of the example, the complete answer to FR-1 … FR-7. Step 1 is the same car park with only spots; see Building it step by step.

VehicleKind and SpotSize are enums. FR-1 is a nine-entry table, so it is a constexpr function next to the enums, not a virtual function on a vehicle class. SpotId and TicketId are small structs around an int, so a spot number cannot be passed where a ticket number is expected; see Strong types.

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

spot.hpp
// FR-1: a motorcycle fits any spot, a car a regular or large one, and a
// van only a large one.
// Takes a vehicle kind and a spot size and answers "may this vehicle park
// in a spot of this size?". It never throws. The whole nine-entry table of
// FR-1 is these few lines: one case per vehicle kind, each saying which
// sizes it accepts. constexpr means the compiler can also work the answer
// out while compiling, when both arguments are known then.
constexpr bool fits(VehicleKind vehicle, SpotSize spot) {
// A switch over an enum class: one `case` per vehicle kind. Each case
// returns, so there is no `break` and no fall-through to the next one.
// With no `default`, the compiler can warn if a new kind is added to
// VehicleKind and is not handled here.
switch (vehicle) {
case VehicleKind::motorcycle:
return true; // every size
case VehicleKind::car:
return spot != SpotSize::small; // regular or large
case VehicleKind::van:
return spot == SpotSize::large; // large only
}
// Every real VehicleKind returned above. A function returning bool must
// still return something on every path, so this line keeps the compiler
// happy; only a value cast from an out-of-range int could reach it.
return false; // not reached for a valid VehicleKind
}

Prices names its three prices, so a call reads Prices{.motorcycle_cents = 100, .car_cents = 250, .van_cents = 400}. Nothing forces a caller to use the names (Prices{100, 250, 400} also compiles), but a call that does use them cannot put the van’s price in the car’s place: C++20 requires designated initializers in declaration order.

Requirement → what a ticket must remember

Requirement Data member C++ type Why this type
FR-4 a ticket has a number id_ TicketId A value; it never changes.
FR-5 the price is by kind vehicle_ VehicleKind A value; the rule needs it for every fee.
INV-1 free the spot at exit spot_ SpotId An ID, not a pointer: the car park’s spots are in a vector, and the ticket should not depend on where.
FR-5 the stay starts at entry entered_ Time (std::chrono::sys_seconds) A point in UTC; now - entered_ is the stay as a duration.
FR-4 the rule at entry rule_ std::shared_ptr<const FeeRule> Shared with the car park and other tickets; const because no one may change a rule once shared. Never null.
FR-7, AC-3.4 used tickets state_ TicketState active, paid, or exited.
FR-6 pay only the difference paid_cents_ std::int64_t The total paid so far, in cents (NFR-2).
FR-7 the 15-minute window paid_at_ std::optional<Time> Empty until the first payment, so “never paid” cannot be confused with “paid at time 0”.

Need → member function

Need Member function Called by Requirement
What is due now? amount_due(Time now) const ParkingLot (pay, exit) FR-6, FR-7
May the driver pay now? may_pay(Time now) const ParkingLot::pay AC-2.4
May the vehicle leave now? may_exit(Time now) const ParkingLot::exit FR-7
Record an accepted payment record_payment(cents, Time now) ParkingLot::pay FR-6
Mark the ticket used close(Time now) ParkingLot::exit AC-3.4
Read the number, spot, state, and so on id(), spot(), state(), … ParkingLot, tests none

Requirement → what the car park must remember

Requirement Data member C++ type Why this type
FR-1, FR-2, FR-3 the spots spots_ std::vector<Spot> Spot n is spots_[n - 1]. Each Spot holds its size and std::optional<TicketId>, the ticket parked there.
UC-2, UC-3 find a ticket by number tickets_ std::vector<Ticket> Ticket n is tickets_[n - 1]. Kept after exit, so a used ticket is recognized (AC-3.4).
FR-5, UC-4 the current rule rule_ std::shared_ptr<const FeeRule> Handed to each new ticket; replaced by set_rule. Never null.
FR-6 the card provider payments_ Payments& Not owned. A reference, because the car park cannot work without one and never switches to another.

Need → member function

Need Member function Called by Requirement
Admit a vehicle enter(VehicleKind, Time now) entrance UC-1
Show what is due amount_due(TicketId, Time now) const pay station UC-2
Pay by card pay(TicketId, const std::string& card_token, Time) pay station UC-2
Open the exit gate exit(TicketId, Time now) exit gate UC-3
Switch the fee rule set_rule(std::shared_ptr<const FeeRule>) operator UC-4
Show the board free_spots(SpotSize) const board FR-3

Every function that a gate calls takes the time as an argument. The car park never reads a clock, so a test can say “at 10:05” instead of waiting 15 minutes (NFR-3).

interface (abstract class) FeeRule

the strategy; a longer stay never costs less

Member functions

  • virtual std::int64_t fee_cents(VehicleKind vehicle, std::chrono::seconds stay) const = 0;

class HourlyRule final

implements FeeRule

Data members

  • Prices per_hour_; per started hour, at least one hour

Member functions

  • explicit HourlyRule(Prices per_started_hour); throws for a negative price

class FlatRule final

implements FeeRule

Data members

  • Prices per_stay_; one price however long

Member functions

  • explicit FlatRule(Prices per_stay); throws for a negative price

interface (abstract class) Payments

the card provider; outside the system

Member functions

  • virtual bool charge(const std::string& card_token, std::int64_t cents) = 0; false if declined
The fee rules and the card provider: two small interfaces

enum class TicketState

Values

  • active
  • paid
  • exited

class Ticket

owns its payment and exit rules

Data members

  • TicketId id_;
  • VehicleKind vehicle_;
  • SpotId spot_; by ID, not a pointer
  • Time entered_;
  • std::shared_ptr<const FeeRule> rule_; shared; the rule at entry; never null
  • TicketState state_ = TicketState::active;
  • std::int64_t paid_cents_ = 0;
  • std::optional<Time> paid_at_; empty until the first payment

Member functions

  • std::int64_t amount_due(Time now) const;
  • bool may_pay(Time now) const;
  • bool may_exit(Time now) const;
  • void record_payment(std::int64_t cents, Time now); throws std::logic_error if not what is due
  • void close(Time now); throws std::logic_error if it may not exit

class ParkingLot

the orchestrator; not thread-safe

Data members

  • std::vector<Spot> spots_; owned; spot n is spots_[n - 1]
  • std::vector<Ticket> tickets_; owned; ticket n is tickets_[n - 1]
  • std::shared_ptr<const FeeRule> rule_; shared; for new entries; never null
  • Payments& payments_; not owned; must outlive the lot

Member functions

  • std::optional<Admission> enter(VehicleKind vehicle, Time now);
  • std::optional<std::int64_t> amount_due(TicketId ticket, Time now) const;
  • PayResult pay(TicketId ticket, const std::string& card_token, Time now);
  • ExitResult exit(TicketId ticket, Time now);
  • void set_rule(std::shared_ptr<const FeeRule> rule);
  • int free_spots(SpotSize size) const;
The ticket and the car park in step 2, with the owner of each member

A rule goes to the class that owns the data it checks. Workflow checks, which call several objects in order, go to the orchestrator.

Rule Lives in Because
Which vehicle fits which spot (FR-1) fits, next to the enums It needs only the two enums.
Which free spot to choose (FR-2) ParkingLot::choose_spot Only the car park sees all the spots.
How much a stay costs (FR-5) HourlyRule, FlatRule Each rule owns its prices and nothing else.
What is due, the 15-minute window, a used ticket (FR-6, FR-7) Ticket The ticket owns paid_cents_, paid_at_, and state_.
Charge the card before recording the payment (AC-2.3) ParkingLot::pay It is the order of calls to two objects: a workflow.
Free the spot when the ticket closes (INV-1) ParkingLot::exit The car park owns both the spot and the ticket.

The ticket does not know the car park, and the fee rule knows neither. Apart from the IDs a spot and its ticket hold for each other, every dependency points one way: ParkingLot → Ticket → FeeRule.

Expected outcomes are values; mistakes are exceptions

Section titled “Expected outcomes are values; mistakes are exceptions”

A refused vehicle, a declined card, and an unpaid ticket at the exit are normal events at a car park, and the gate must show something for each. They are returned as values: std::optional<Admission>, PayResult with a PayStatus, and ExitResult with an ExitStatus. Exceptions are kept for programming mistakes: a null rule, a negative price, a time before the ticket’s entry, or calling record_payment when nothing is due. See Errors and contracts.

Trace ticket 2 from the demo (a van, hourly rule of 4.00 an hour) through the finished design:

  1. 09:10 enter(van, 09:10). choose_spot skips small and regular (fits is false) and finds spot 6, the only large spot. → ticket 2 is active, spot 6 holds ticket 2, large free count 0.
  2. 12:05 pay(2, "declined", 12:05). may_pay is true; amount_due is 3 started hours × 400 = 1200. charge returns false. → returns declined; the ticket is unchanged (AC-2.3).
  3. 12:06 pay(2, card, 12:06). Due 1200; charge returns true; record_payment(1200, 12:06). → paid, paid_cents_ 1200, paid_at_ 12:06.
  4. 12:30 exit(2, 12:30). 12:30 is after 12:06 + 15 minutes, so the window is over. The fee is now 4 started hours × 400 = 1600; due is 1600 − 1200 = 400. → returns payment_needed with 400; the spot is still taken (AC-3.3).
  5. 12:32 pay(2, card, 12:32). Due 400, charged. → paid_cents_ 1600, paid_at_ 12:32.
  6. 12:35 exit(2, 12:35). Inside the new window, due 0. close. → the ticket is exited; spot 6 holds nothing; large free count 1.

Each step uses only the members in the outlines above, plus the private helper choose_spot, which is how you check that the design is complete.

The simplest design that meets the requirements is one class that runs the use cases (ParkingLot), one class with a lifecycle (Ticket), and two interfaces where something genuinely varies (FeeRule) or lives outside (Payments). There is no layering beyond that: the gates and pay stations call ParkingLot directly. A larger system would put an application layer between devices and this core; one car park does not need it.

Three choices are worth comparing in detail.

Fee rules: where does the price come from?

Section titled “Fee rules: where does the price come from?”

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

fees.hpp
// How a car park prices a stay. A rule is immutable once made, so one
// rule object can be shared by every ticket issued under it.
// Contract: the fee never goes down as the stay gets longer. Paying the
// difference after the exit window has closed (FR-6) relies on this.
// FeeRule is an interface (an abstract base class): it says what every rule
// can do, and each concrete rule below says how. A ticket holds a pointer
// to "some FeeRule" and never needs to know which one it is; this is the
// Strategy pattern.
class FeeRule {
public:
// A virtual destructor, because a rule may be destroyed through a
// pointer to FeeRule. Without `virtual`, deleting an HourlyRule through
// a FeeRule* would be undefined behaviour. (A std::shared_ptr made from
// an HourlyRule remembers the real type anyway, but an interface should
// be safe however it is held.)
virtual ~FeeRule() = default;
// The price in cents for a stay of `stay` seconds by this kind of
// vehicle. `virtual ... = 0` makes it pure virtual: FeeRule has no
// body for it, so FeeRule itself cannot be created, and every concrete
// rule must provide one. `const` promises that pricing a stay does not
// change the rule, which is what lets many tickets share one rule.
// Both rules below throw std::invalid_argument for a negative stay.
virtual std::int64_t fee_cents(VehicleKind vehicle, std::chrono::seconds stay) const = 0;
};
// A price per started hour, by vehicle kind.
// `final` means no class may derive from HourlyRule; `public FeeRule` means
// an HourlyRule can be used anywhere a FeeRule is expected.
class HourlyRule final : public FeeRule {
public:
// Throws std::invalid_argument if a price is negative.
// `explicit` stops a Prices from silently turning into an HourlyRule
// where a rule is expected; the caller has to name the rule they want.
explicit HourlyRule(Prices per_started_hour);
// started_hours(stay) times the vehicle's hourly price. `override` asks
// the compiler to check that this really replaces FeeRule::fee_cents
// (a typo in the parameters would then be an error, not a new function).
std::int64_t fee_cents(VehicleKind vehicle, std::chrono::seconds stay) const override;
private:
Prices per_hour_;
};
// One price per stay, however long, by vehicle kind: for event days.
class FlatRule final : public FeeRule {
public:
// Throws std::invalid_argument if a price is negative.
explicit FlatRule(Prices per_stay);
// The vehicle's price, whatever the length of the stay; a stay of zero
// seconds costs the same as one of ten hours.
std::int64_t fee_cents(VehicleKind vehicle, std::chrono::seconds stay) const override;
private:
Prices per_stay_;
};

Why std::shared_ptr<const FeeRule> and not the alternatives:

  • std::unique_ptr<FeeRule> has one owner. Here the car park and every ticket issued under a rule need it, for different lengths of time. See Smart pointers.
  • A raw pointer to a rule owned elsewhere works if the car park keeps every rule it has ever used for its whole life, say in a std::vector<std::unique_ptr<const FeeRule>>; rules are few. But then a ticket is valid only while that car park exists, and the car park becomes an archive of old rules. shared_ptr says “alive while anyone needs it” directly.
  • A copy of the rule in each ticket would need a virtual clone() and one heap allocation per ticket, for an object that never changes.
  • const matters. Shared mutable state is what makes shared ownership dangerous; a rule nobody can change after it is shared is safe to read from several threads. ParkingLot::rule_ itself would still need a lock, because set_rule replaces it.

Do the rules belong to the ticket or to the car park?

Section titled “Do the rules belong to the ticket or to the car park?”
  • No Singleton. “There is only one car park” is true of the client’s business, not of the program: every test builds its own ParkingLot. A global instance would make tests share state. See Singleton.
  • No Floor, Gate, or Display classes. Gates and boards call functions; they hold no state the system needs. Floors arrive in change 1, and even then they are a number on each spot.
  • No State pattern for the ticket. The ticket has three states and each rule is one line; a switch on TicketState is clearer than three state classes. The State pattern pays off when each state has substantial behaviour of its own; see also State machines.
  • No index of free spots. choose_spot scans the spots. For about 2,000 spots that is a few thousand comparisons per entry (not measured). A free list per size would be faster, but it is a second copy of the truth that must agree with the spots, which is one more thing INV-2 would have to cover.

The example is in examples/case-studies/parking-lot/ in four steps. Each step is a complete program with its own tests; a step copies the previous one and changes only what its requirements need. Steps 1 and 2 are below; steps 3 and 4 are the two changes in When the requirements change.

The first step leaves out tickets, money, and time entirely. It answers one question: given a plan of spot sizes, which spot does each vehicle get? Getting allocation right on its own, with its own tests, means later steps can rely on it.

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

parking_lot.hpp
// Owns its spots by value. Not thread-safe: the car park's server handles
// one request at a time (an assumption in the scope).
// The step 1 car park: a row of numbered spots, each one free or taken.
// It answers two questions (where does this vehicle go? how many spots of
// a size are free?) and records arrivals and departures. Nothing else:
// no tickets, money, or clock yet.
class ParkingLot {
public:
// One entry per spot; spot n is spots[n - 1].
// The plan is read once and copied into spots_, all spots free. The
// plan is taken by const reference (no copy of the argument itself).
// `explicit` stops a bare vector from turning into a ParkingLot by
// accident. An empty plan is allowed: a car park that admits nobody.
explicit ParkingLot(const std::vector<SpotSize>& spots);
// FR-1, FR-2: the smallest free spot the vehicle fits, lowest number
// first within a size; nothing if no spot fits.
// std::optional<SpotId> either holds a spot number or is empty
// (std::nullopt). Empty means "full for this vehicle", an ordinary
// answer, so it is not an exception. On success the spot is marked taken.
std::optional<SpotId> park(VehicleKind vehicle);
// Frees a taken spot. Throws std::invalid_argument for an unknown
// or free spot.
void leave(SpotId spot);
// FR-3: for the board at the entrance.
int free_spots(SpotSize size) const;
private:
// One spot as the car park sees it: its size, fixed by the plan, and
// whether a vehicle is in it. A struct inside the class, because nothing
// outside ParkingLot needs it.
struct Spot {
SpotSize size;
bool taken = false; // every spot starts free
};
// The spots in plan order: spot number n is spots_[n - 1]. Held by
// value, so the car park owns them and nothing has to be freed.
std::vector<Spot> spots_;
};

park returns std::optional<SpotId>: a full car park is a normal answer, not an error. leave throws std::invalid_argument for a spot that is free or does not exist, because a caller that does that has a bug.

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

parking_lot.cpp
// Gives the vehicle the smallest size of spot it fits that has a free spot,
// and within that size the lowest-numbered free spot. Marks the spot taken
// and returns its number, or returns std::nullopt (and changes nothing) if
// no fitting spot is free. Never throws.
std::optional<SpotId> ParkingLot::park(VehicleKind vehicle) {
// The outer loop tries the sizes in order, smallest first. The braces
// make a short list of the three sizes for the loop to walk through.
for (const SpotSize size : {SpotSize::small, SpotSize::regular, SpotSize::large}) {
// `continue` skips the rest of this pass: a car never looks at the
// small spots at all.
if (!fits(vehicle, size)) continue;
// The inner loop walks the spots from the lowest number up.
// std::size_t is the unsigned type the vector uses for indexes.
for (std::size_t i = 0; i < spots_.size(); ++i) {
// A reference, not a copy, so setting `taken` below changes the
// spot stored in spots_.
Spot& spot = spots_[i];
if (spot.size == size && !spot.taken) {
spot.taken = true;
// Index i is spot number i + 1. static_cast<int> turns the
// unsigned index into the int that SpotId holds. Returning
// here ends both loops at once: the first match wins.
return SpotId{static_cast<int>(i) + 1};
}
}
}
// Every fitting size was tried and none had a free spot.
return std::nullopt;
}

The outer loop goes through the sizes from smallest to largest and skips those the vehicle does not fit; the inner loop finds the lowest free spot of that size. That is FR-2 written almost word for word. Two of the tests:

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

test_step1.cpp
// LLD_TEST(name) defines one test, LLD_CHECK(condition) records a failure if
// the condition is false, and LLD_CHECK_EQ(actual, expected) does the same
// for "actual == expected" and prints both values when they differ. They
// come from the site's small test header, lld_test.hpp. small_lot(), a
// helper in this file, builds spots 1-2 small, 3-4 regular, and 5 large.
// AC-1.2: each vehicle gets the smallest size it fits, lowest number first.
// park returns an optional; comparing it with SpotId{3} is true only if it
// holds a spot and that spot is 3.
LLD_TEST(ac_1_2_smallest_fitting_size_then_lowest_number) {
ParkingLot lot = small_lot();
// A car skips the small spots, so it gets the first regular one, 3. The
// motorcycle then gets small spot 1, not a regular one.
LLD_CHECK(lot.park(VehicleKind::car) == SpotId{3});
LLD_CHECK(lot.park(VehicleKind::motorcycle) == SpotId{1});
LLD_CHECK(lot.park(VehicleKind::car) == SpotId{4});
// Regular spots are full: the next car gets the large spot.
LLD_CHECK(lot.park(VehicleKind::car) == SpotId{5});
}
// AC-1.3: once the only large spot is taken, a second van is refused, even
// though four smaller spots are free. The last check proves the refusal
// did not quietly take a small spot instead.
LLD_TEST(ac_1_3_no_fitting_spot_means_no_entry_even_if_others_are_free) {
ParkingLot lot = small_lot();
LLD_CHECK(lot.park(VehicleKind::van) == SpotId{5});
LLD_CHECK(lot.park(VehicleKind::van) == std::nullopt);
LLD_CHECK_EQ(lot.free_spots(SpotSize::small), 2);
}

Step 2: tickets, fees, payment, and exit (FR-4 … FR-7)

Section titled “Step 2: tickets, fees, payment, and exit (FR-4 … FR-7)”

Step 2 adds the fee rules, the ticket, the card provider, and the four use cases. The fee rules come first, because the ticket depends on them and they depend on nothing. “Per started hour, minimum one hour” is easy to get wrong at the boundaries, so it is one small function:

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

fees.cpp
// How many hours a stay has started, counting at least one. Takes the stay
// as a std::chrono::seconds (a number of seconds with its unit in the type)
// and returns a plain count. Throws std::invalid_argument for a negative
// stay, which would mean an exit time before the entry time.
std::int64_t started_hours(std::chrono::seconds stay) {
// Lets this function write `0s` for "zero seconds" (a chrono literal).
using namespace std::chrono_literals;
if (stay < 0s) throw std::invalid_argument("stay is negative");
// stay.count() is the plain number of seconds. Integer division drops
// any remainder (it rounds down), so adding 3'599 (one second short of
// an hour) first makes it round up instead: 3'600 s gives 1, 3'601 s
// gives 2. The ' marks are digit separators, ignored by the compiler.
const std::int64_t hours = (stay.count() + 3'599) / 3'600; // rounds up
// A stay of 0 seconds gives 0 above, but the rule is "minimum one hour".
return hours == 0 ? 1 : hours;
}

Adding 3,599 seconds before dividing rounds up, so 3,600 seconds is one hour and 3,601 seconds is two. A stay of 0 seconds still counts as one hour.

The card provider is an interface with one function. The real provider is a network service, out of scope; the tests and the demo use stand-ins that approve every card except the token "declined". See Test doubles and seams.

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

payments.hpp
// The car park's only view of the card provider: an interface with one
// function. ParkingLot holds a reference to "some Payments" and never knows
// whether it is the real network service, the demo's stand-in, or a test's
// fake that records every charge. Swapping one for another needs no change
// to ParkingLot; this is the seam the tests use.
class Payments {
public:
// Virtual, so a stand-in deleted through a Payments pointer is
// destroyed correctly.
virtual ~Payments() = default;
// `= 0` (pure virtual): Payments has no body for charge, and each
// provider must supply its own. It is not const: charging a card is
// an action with an effect, and a fake changes its own record.
// Takes the amount from the card; false if the provider declines.
// card_token is what the pay station's reader gives, never a card
// number.
virtual bool charge(const std::string& card_token, std::int64_t cents) = 0;
};

The ticket:

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

ticket.hpp
// Holds the facts of one stay and enforces its lifecycle (FR-6, FR-7):
// active -> paid -> exited. A paid ticket can pay again if more is due
// once its exit window has closed, and a ticket with nothing due at all
// (a price of 0) can exit without paying. Shares its fee rule with the lot and with every other
// ticket issued under the same rule, so the rule stays alive as long as
// any of them needs it (FR-4).
class Ticket {
public:
// How long a ticket may stay inside after paying before it owes more
// (FR-7). One value for every ticket (static), fixed at compile time
// (constexpr), with its unit in its type (std::chrono::minutes).
static constexpr std::chrono::minutes exit_window{15};
// Throws std::invalid_argument if rule is null.
// `rule` is a std::shared_ptr: a pointer that shares ownership. Every
// copy counts as one owner, and the FeeRule is destroyed only when the
// last owner lets go. The ticket takes the parameter by value and moves
// it into rule_, so the caller's copy becomes this ticket's share.
// `const FeeRule` means the ticket can use the rule but not change it.
// Every ticket starts active, with nothing paid.
Ticket(TicketId id, VehicleKind vehicle, SpotId spot, Time entered,
std::shared_ptr<const FeeRule> rule);
TicketId id() const { return id_; }
VehicleKind vehicle() const { return vehicle_; }
SpotId spot() const { return spot_; }
TicketState state() const { return state_; }
std::int64_t paid_cents() const { return paid_cents_; }
// The fee for the stay so far, minus what has been paid. 0 while the
// exit window is open, and after exit. Throws std::invalid_argument
// if now is before entry.
// Also throws std::logic_error if the rule would make the amount
// negative (INV-4), which only a rule that breaks its contract can do.
// Every question below is asked "at time now": the ticket has no clock
// of its own, so a test can ask about any moment it likes.
std::int64_t amount_due(Time now) const;
// Not exited, and something is due.
bool may_pay(Time now) const;
// Not exited, and nothing is due.
bool may_exit(Time now) const;
// Both may throw what amount_due throws, since they call it.
// The two functions that change a ticket. Each checks its rule first
// and throws before changing anything, so a refused call leaves the
// ticket as it was. ParkingLot checks first, so in a correct program
// these never throw.
// Throws std::logic_error unless may_pay(now) and cents == amount_due(now).
// On success: adds cents to paid_cents_, remembers now as the latest
// payment time (which opens a new exit window), and sets state paid.
void record_payment(std::int64_t cents, Time now);
// Throws std::logic_error unless may_exit(now). On success: state exited.
void close(Time now);
private:
TicketId id_;
VehicleKind vehicle_;
SpotId spot_;
Time entered_;
std::shared_ptr<const FeeRule> rule_; // the rule in force at entry; never null
TicketState state_ = TicketState::active;
std::int64_t paid_cents_ = 0;
// The latest payment, once there is one. std::optional because a new
// ticket has no payment time; it holds a value whenever state_ is paid
// (record_payment sets both together), and once set it is never cleared.
std::optional<Time> paid_at_; // the latest payment, once there is one
};

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

ticket.cpp
// The one place the payment rule lives. Each `if` either throws or returns
// early, so the fee is worked out only for a ticket that is active, or
// paid with its window over.
std::int64_t Ticket::amount_due(Time now) const {
if (now < entered_) throw std::invalid_argument("time is before entry");
if (state_ == TicketState::exited) return 0;
// Inside the exit window nothing is due, even if a new hour has begun.
// `<=` makes the window include its last second: paid at 11:45, still
// free at exactly 12:00. *paid_at_ reads the time out of the optional;
// that is safe here because a paid ticket always has one.
if (state_ == TicketState::paid && now <= *paid_at_ + exit_window) return 0;
// now - entered_ is the length of the stay, in seconds. `rule_->` calls
// fee_cents on whichever rule this ticket was issued with (hourly or
// flat); the virtual call picks the right version. The fee covers the
// whole stay, so what was already paid is taken off.
const std::int64_t due = rule_->fee_cents(vehicle_, now - entered_) - paid_cents_;
// INV-4. Only a rule that breaks its contract can make this negative.
if (due < 0) throw std::logic_error("fee rule charged less for a longer stay");
return due;
}
// An exited ticket owes 0, so it can never pay: "not exited" comes free.
bool Ticket::may_pay(Time now) const { return amount_due(now) > 0; }
// Here "not exited" must be checked by itself, because an exited ticket
// also owes 0 and would otherwise be let out a second time.
bool Ticket::may_exit(Time now) const {
return state_ != TicketState::exited && amount_due(now) == 0;
}
// Check, then change. The payment must be for exactly what is due: no part
// payments, no overpaying. `||` stops at the first true part, so when
// may_pay is false amount_due is not called a second time.
void Ticket::record_payment(std::int64_t cents, Time now) {
if (!may_pay(now) || cents != amount_due(now)) {
throw std::logic_error("payment does not match what is due");
}
paid_cents_ += cents; // `+=`, not `=`: a second payment adds to the first
paid_at_ = now; // a new window starts from this payment
state_ = TicketState::paid;
}
// The ticket's last change. Nothing else is cleared: the spot is freed by
// ParkingLot, which owns the spots.
void Ticket::close(Time now) {
if (!may_exit(now)) throw std::logic_error("ticket may not exit now");
state_ = TicketState::exited;
}

amount_due holds the whole payment rule. A ticket that has exited owes nothing. A paid ticket inside its window owes nothing, even if a new hour has started. Otherwise the ticket owes the fee so far minus what it has paid. may_exit is then simple: the ticket has not exited and nothing is due. That one rule covers a ticket paid within 15 minutes, a ticket paid long ago under a flat rule (nothing more is due), and a motorcycle whose price is zero (it never needs the pay station).

If a rule ever charged less for a longer stay, paid_cents_ could exceed the fee and the amount due would be negative. That would break INV-4, and the ticket throws std::logic_error rather than return a negative amount that a gate might treat as a refund.

How this code works: Ticket::amount_due, step by step

amount_due asks up to four questions, in this order, and the first one that settles the answer ends the function:

  1. Is now before the entry? Then the caller has a bug, and the ticket throws std::invalid_argument.
  2. Has the ticket exited? Then nothing is due, ever again.
  3. Is it paid, and is now inside the window? The window runs from the latest payment to 15 minutes after it, last second included (<=). Inside it, nothing is due.
  4. Otherwise the fee for the whole stay so far, from the ticket’s own rule, minus everything paid. If that is negative, the rule broke its contract and the ticket throws std::logic_error.

The other four functions are built on it. may_pay is “something is due”. may_exit is “not exited, and nothing is due”. record_payment and close check those first and throw if they are false, so they can never leave a ticket half-changed.

A worked example: ticket 2 in the demo. A van enters at 09:10 under the hourly rule, 4.00 an hour. The “Due” column is what amount_due returns at that moment, before any payment made then.

Time State before Which question decides Stay Fee Paid before Due
12:05 active 4: the fee 2 h 55 min 12.00 0 12.00
12:06 active 4: pays 12.00, window to 12:21 2 h 56 min 12.00 0 12.00
12:30 paid 4: window over 3 h 20 min 16.00 12.00 4.00
12:32 paid 4: pays 4.00, window to 12:47 3 h 22 min 16.00 12.00 4.00
12:35 paid 3: inside the window 3 h 25 min not worked out 16.00 0

At 12:05 the card is declined, so nothing changes and 12.00 is still due a minute later. At 12:35 nothing is due, so may_exit is true, the gate opens, and close sets the state to exited. From then on question 2 answers every call with 0.

The car park:

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

parking_lot.hpp
// The orchestrator: owns the spots and the tickets, decides which spot a
// vehicle gets, and runs each use case. Not thread-safe: the car park's
// server handles one request at a time (an assumption in the scope).
class ParkingLot {
public:
// payments is not owned and must outlive the lot. Throws
// std::invalid_argument if rule is null.
// `spots` is the plan, one size per spot, copied in with every spot
// free. `rule` is the first fee rule; the lot becomes one of its
// owners. `payments` is a plain reference (&): the lot only uses the
// provider, so whoever created it must keep it alive longer.
ParkingLot(const std::vector<SpotSize>& spots, std::shared_ptr<const FeeRule> rule,
Payments& payments);
// The use cases. Expected refusals (car park full, card declined,
// unknown ticket, money due) are returned as values, not thrown: an
// empty optional, or a status in PayResult or ExitResult. Every `now`
// comes from the caller, which keeps the tests free of a real clock.
// A `now` before a ticket's entry is a caller's bug: amount_due, pay,
// and exit then let std::invalid_argument from the ticket through.
// enter: a ticket and a spot, or nothing if no fitting spot is free.
// amount_due: nothing for an unknown ticket number. set_rule: changes
// the rule for later entries only; throws std::invalid_argument if null.
std::optional<Admission> enter(VehicleKind vehicle, Time now); // UC-1
std::optional<std::int64_t> amount_due(TicketId ticket, Time now) const; // UC-2
PayResult pay(TicketId ticket, const std::string& card_token, Time now); // UC-2
ExitResult exit(TicketId ticket, Time now); // UC-3
void set_rule(std::shared_ptr<const FeeRule> rule); // UC-4
int free_spots(SpotSize size) const; // FR-3
private:
// A spot is free when `ticket` is empty. It stores the ticket's number,
// not a pointer to it: a pointer into tickets_ would dangle as soon as
// the vector grew and moved its elements to a new block of memory.
struct Spot {
SpotSize size;
std::optional<TicketId> ticket; // the ticket parked here, if any
};
// The step 1 search, with "free" now meaning "holds no ticket". Only
// chooses; enter marks the spot.
std::optional<SpotId> choose_spot(VehicleKind vehicle) const; // FR-2
// Turns a ticket number into its position in tickets_ (number - 1),
// after checking that the number was really issued.
std::optional<std::size_t> index_of(TicketId ticket) const; // nothing if unknown
// Everything the lot owns is held by value in vectors, so nothing needs
// freeing by hand. Tickets are never removed, which is what keeps
// "ticket n is tickets_[n - 1]" true and lets exit report a used ticket.
std::vector<Spot> spots_; // spot n is spots_[n - 1]
std::vector<Ticket> tickets_; // ticket n is tickets_[n - 1]; kept after exit
std::shared_ptr<const FeeRule> rule_; // for new entries; never null
// A reference member: it must be bound in the constructor and can never
// be pointed at another provider afterwards.
Payments& payments_; // not owned
};

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

parking_lot.cpp
// UC-1. Chooses a spot, issues the next ticket under the current rule, and
// marks the spot as holding that ticket. Returns the ticket and spot, or
// std::nullopt with nothing changed if no fitting spot is free.
std::optional<Admission> ParkingLot::enter(VehicleKind vehicle, Time now) {
const std::optional<SpotId> spot = choose_spot(vehicle);
if (!spot) return std::nullopt; // AC-1.3: nothing changes
// Tickets are numbered 1, 2, 3, ... in order, so the next number is one
// more than the count issued so far. A refused vehicle (above) uses none.
const TicketId id{static_cast<int>(tickets_.size()) + 1};
// emplace_back builds the Ticket directly inside the vector from these
// constructor arguments. rule_ is copied, not moved: the lot keeps its
// own share, and the ticket gets another one. *spot reads the SpotId
// out of the optional (safe: the empty case returned above).
tickets_.emplace_back(id, vehicle, *spot, now, rule_); // shares the current rule
// spot->value is the spot's number; spot n lives at index n - 1.
spots_[static_cast<std::size_t>(spot->value) - 1].ticket = id;
return Admission{id, *spot};
}

A refused vehicle returns before anything changes, so no ticket number is used (AC-1.3). The new ticket receives a copy of rule_, which adds one owner to the current rule.

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

parking_lot.cpp
// UC-2. Charges the card for exactly what is due and records it on the
// ticket. Refuses, changing nothing, for an unknown or used ticket, when
// nothing is due, and when the card is declined. Throws
// std::invalid_argument (from the ticket) if now is before the entry.
PayResult ParkingLot::pay(TicketId ticket, const std::string& card_token, Time now) {
const std::optional<std::size_t> i = index_of(ticket);
// `return {PayStatus::unknown_ticket};` builds the PayResult in place:
// the status given, and charged_cents left at its default of 0.
if (!i) return {PayStatus::unknown_ticket};
// A reference to the ticket inside the vector, so record_payment below
// changes the stored ticket and not a copy. *i is the index inside the
// optional, known to be there after the check above.
Ticket& t = tickets_[*i];
if (t.state() == TicketState::exited) return {PayStatus::used};
if (!t.may_pay(now)) return {PayStatus::nothing_due};
const std::int64_t due = t.amount_due(now);
// The only call that leaves the system. It comes after every check and
// before any change, so a decline (or an exception from the provider)
// leaves the ticket exactly as it was.
if (!payments_.charge(card_token, due)) {
return {PayStatus::declined}; // AC-2.3: nothing changes
}
// `due` and `now` are the same values the checks used, so this call
// cannot throw.
t.record_payment(due, now);
return {PayStatus::paid, due};
}

The order matters. The ticket is checked first, so an unknown or used ticket never reaches the card provider. The card is charged before the payment is recorded, so a declined card leaves the ticket exactly as it was (AC-2.3). If the card provider threw an exception instead of returning false, the ticket would also be unchanged, because nothing has been modified before the call.

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

parking_lot.cpp
// UC-3. Opens the gate for a ticket with nothing due, closes the ticket,
// and frees its spot. Refuses, changing nothing, for an unknown or used
// ticket and when money is due (the result then says how much). Throws
// std::invalid_argument (from the ticket) if now is before the entry.
ExitResult ParkingLot::exit(TicketId ticket, Time now) {
const std::optional<std::size_t> i = index_of(ticket);
if (!i) return {ExitStatus::unknown_ticket};
Ticket& t = tickets_[*i]; // safe: nothing below adds to tickets_
if (t.state() == TicketState::exited) return {ExitStatus::used};
// The gate stays shut and the driver is told what to pay.
if (!t.may_exit(now)) return {ExitStatus::payment_needed, t.amount_due(now)};
t.close(now);
// Find the ticket's spot by number and empty its optional with reset():
// the spot holds no ticket, so it is free again.
spots_[static_cast<std::size_t>(t.spot().value) - 1].ticket.reset(); // INV-1
return {ExitStatus::opened};
}

Ticket& t = tickets_[*i] is safe here because nothing is added to tickets_ while t is in use; adding a ticket could move the vector’s elements and leave t dangling. That is also why a spot stores a TicketId and not a Ticket*: the pointer would dangle the first time tickets_ grew.

Flawed (intentional)Demonstrates a mistake on purpose. Do not copy it; see the corrected version.

// The idea: let each spot point straight at its ticket, so exit could
// reach the ticket from the spot without looking anything up.
struct Spot {
SpotSize size;
Ticket* ticket = nullptr; // flawed: points into tickets_
};
// In enter(): the new ticket is added, then its address is stored.
tickets_.emplace_back(id, vehicle, *spot, now, rule_);
// tickets_.back() is the ticket just added; & takes its address. That
// address is where the ticket lives inside the vector's memory today.
spots_[index].ticket = &tickets_.back();
// The next emplace_back may reallocate tickets_. If it does, every
// Spot::ticket stored so far points at freed memory.
// Why: a vector keeps its elements in one block. When the block is full,
// emplace_back gets a bigger block, moves every ticket into it, and frees
// the old one. The spots still hold the old addresses. Nothing warns: the
// pointers look fine, and using one later is undefined behaviour (it may
// read garbage, crash, or seem to work). How often this happens depends on
// the vector's capacity, so a small test can pass by luck.

The corrected version, as in the example’s header, stores the ticket’s number; anything that needs the ticket looks it up by number:

IllustrativeA fragment for explanation; not compiled on its own.

struct Spot {
SpotSize size;
std::optional<TicketId> ticket; // the ticket parked here, if any
};
// In enter():
tickets_.emplace_back(id, vehicle, *spot, now, rule_);
// A number, not an address. Ticket n is always tickets_[n - 1], wherever
// the vector keeps its elements, so the lookup is done when it is needed.
spots_[index].ticket = id; // still correct however often tickets_ grows

With an ID, the spot and the ticket refer to each other without either depending on where the other is stored. See References, pointers, and ownership.

The states of a ticket and the calls that move it between them
Text description of the diagram

Three states. A ticket starts as active when a vehicle enters. From active, pay moves it to paid if something is due and the card is accepted. From paid, pay keeps it paid if the window is over, more is due, and the card is accepted. From active, exit moves it to exited only if the fee so far is zero (a free vehicle kind). From paid, exit moves it to exited if nothing is due. Exited is final. A declined card, a pay when nothing is due, and an exit when something is due change no state.

Diagram source (Mermaid)
stateDiagram-v2
[*] --> active : enter
active --> paid : pay [something due, card accepted]
paid --> paid : pay [window over, more due, card accepted]
active --> exited : exit [fee so far is 0]
paid --> exited : exit [nothing due]
exited --> [*]
Entry, payment, and exit for ticket 1 in the demo
Text description of the diagram

Five participants: a gate or pay station, ParkingLot, Ticket, FeeRule, and Payments. At 09:00 the device calls enter for a car; ParkingLot chooses spot 3, creates ticket 1 with the current rule, and returns an admission for ticket 1 at spot 3. At 11:45 the device calls pay for ticket 1; ParkingLot asks the ticket whether it may pay and what is due; the ticket asks its FeeRule for the fee of a car for 2 hours 45 minutes, which is 750; the ticket answers true and 750. ParkingLot asks Payments to charge 750 to the card; Payments returns true; ParkingLot records the payment on the ticket and returns “paid 750”. At 11:50 the device calls exit; ParkingLot asks whether the ticket may exit; the ticket answers true because 11:50 is inside the window; ParkingLot closes the ticket, frees spot 3, and returns “opened”.

Diagram source (Mermaid)
sequenceDiagram
participant Dev as gate or pay station
participant Lot as ParkingLot
participant T as Ticket
participant Rule as FeeRule
participant Pay as Payments
Dev->>Lot: enter(car, 09:00)
Lot->>Lot: choose_spot(car) gives spot 3
Lot->>T: create ticket 1 with the current rule
Lot-->>Dev: Admission, ticket 1, spot 3
Dev->>Lot: pay(ticket 1, card, 11:45)
Lot->>T: may_pay(11:45), amount_due(11:45)
T->>Rule: fee_cents(car, 2 h 45 min)
Rule-->>T: 750
T-->>Lot: true, 750
Lot->>Pay: charge(card, 750)
Pay-->>Lot: true
Lot->>T: record_payment(750, 11:45)
Lot-->>Dev: paid 750
Dev->>Lot: exit(ticket 1, 11:50)
Lot->>T: may_exit(11:50)
T-->>Lot: true, inside the window
Lot->>T: close(11:50)
Lot->>Lot: spot 3 holds no ticket
Lot-->>Dev: opened

The demo’s car park has spots 1–2 small, 3–5 regular, and 6 large. It starts with the hourly rule (1.00, 2.50, and 4.00 an hour for a motorcycle, a car, and a van) and switches to the flat event rule (3.00, 8.00, 12.00) at 11:30.

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

main.cpp
// The calls enter, pay, and leave below are small helpers earlier in this
// file: each calls the ParkingLot function of (nearly) the same name and
// prints one line of the output. at(9h) turns "9 hours after midnight"
// into a Time; 9h + 10min is 09:10 (chrono literals, so the units are
// checked by the compiler). DemoPayments approves every card token except
// "declined".
int main() {
// Local objects are destroyed in reverse order of declaration, so the
// lot (declared second) is gone before the payments object it refers to.
DemoPayments payments; // outlives the lot: declared first
// Spots 1-2 small, 3-5 regular, 6 large. std::make_shared<HourlyRule>
// creates the rule and returns a shared_ptr to it, which converts to the
// std::shared_ptr<const FeeRule> the lot asks for. The lot is then the
// rule's only owner, until tickets take shares of it.
ParkingLot lot({SpotSize::small, SpotSize::small, SpotSize::regular, SpotSize::regular,
SpotSize::regular, SpotSize::large},
std::make_shared<HourlyRule>(
Prices{.motorcycle_cents = 100, .car_cents = 250, .van_cents = 400}),
payments);
// Ticket 1 (car, spot 3) and ticket 2 (van, spot 6). The second van is
// refused: spot 6 was the only large spot.
enter(lot, VehicleKind::car, at(9h));
enter(lot, VehicleKind::van, at(9h + 10min));
enter(lot, VehicleKind::van, at(9h + 20min));
std::cout << "board: small " << lot.free_spots(SpotSize::small) << ", regular "
<< lot.free_spots(SpotSize::regular) << ", large "
<< lot.free_spots(SpotSize::large) << '\n';
// The lot does not track the time of day: the "11:30" is only printed.
// set_rule replaces the lot's own pointer. Tickets 1 and 2 still hold
// shares of the hourly rule, so it stays alive and they keep using it.
std::cout << "11:30 event prices from now on\n";
lot.set_rule(std::make_shared<FlatRule>(
Prices{.motorcycle_cents = 300, .car_cents = 800, .van_cents = 1'200}));
enter(lot, VehicleKind::car, at(11h + 40min)); // ticket 3, flat rule
pay(lot, 1, "card-a", at(11h + 45min)); // entered under the hourly rule
leave(lot, 1, at(11h + 50min));
pay(lot, 2, "declined", at(12h + 5min)); // refused, ticket unchanged
pay(lot, 2, "card-b", at(12h + 6min)); // 2 h 56 min: 3 hours of 4.00
leave(lot, 2, at(12h + 30min)); // the 15 minutes ended at 12:21
// At 12:30 the van has stayed 3 h 20 min (it entered at 09:10), so a
// fourth hour has started: 4 x 4.00 minus the 12.00 paid is 4.00 due.
// Paying it at 12:32 opens a new window, so the exit at 12:35 opens.
pay(lot, 2, "card-b", at(12h + 32min));
leave(lot, 2, at(12h + 35min));
pay(lot, 3, "card-c", at(15h)); // flat rule: 8.00 however long
leave(lot, 3, at(15h + 5min));
leave(lot, 1, at(15h + 6min)); // ticket 1 left at 11:50: already used
}
Expected output
09:00 car enters: ticket 1, spot 3
09:10 van enters: ticket 2, spot 6
09:20 van enters: no spot it fits
board: small 2, regular 2, large 0
11:30 event prices from now on
11:40 car enters: ticket 3, spot 4
11:45 ticket 1 pays: paid 7.50
11:50 ticket 1 at the exit: gate opens
12:05 ticket 2 pays: card declined
12:06 ticket 2 pays: paid 12.00
12:30 ticket 2 at the exit: gate stays shut, 4.00 due
12:32 ticket 2 pays: paid 4.00
12:35 ticket 2 at the exit: gate opens
15:00 ticket 3 pays: paid 8.00
15:05 ticket 3 at the exit: gate opens
15:06 ticket 1 at the exit: ticket already used

Trace of the less obvious lines:

  1. 09:20 a second van → the only large spot is taken; smaller spots do not fit a van → refused, nothing changes (AC-1.3).
  2. 11:30 the flat rule → only the car park’s pointer changes; tickets 1 and 2 keep the hourly rule (AC-4.2).
  3. 11:45 ticket 1 pays → 2 h 45 min is 3 started hours × 250 → 7.50, by the hourly rule it was issued with, not the flat 8.00.
  4. 12:05 and 12:06 ticket 2 → the declined card changes nothing; the second card pays 3 × 400 → 12.00.
  5. 12:30 ticket 2 at the exit → 24 minutes after paying, and a fourth hour has started → 4.00 due, gate shut (AC-3.3).
  6. 15:00 ticket 3 → entered at 11:40 under the flat rule → 8.00 for 3 h 20 min (AC-4.1).
  7. 15:06 ticket 1 again → it exited at 11:50 → “already used” (AC-3.4).

Each test name starts with the acceptance criterion it checks, so the traceability table can point at it. The tests use the site’s small test framework and a FakePayments test double that records every charge, so a test can check that a card was not charged.

Boundaries. Exactly one hour, and one second more. Exactly 15 minutes after paying, when a new hour has also started. A price of zero.

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

test_step2.cpp
// Helpers defined earlier in this file: FakePayments approves every card
// token except "declined" and records each amount it charged in its
// `charges` vector. hourly() and flat() make the demo's two rules (car
// 250 an hour; car 800 flat, van 1'200 flat). `plan` is spots 1-2 small,
// 3-4 regular, 5 large. at(9h) is 09:00, and at(10h) + 1s is 10:00:01.
// AC-2.1: the hourly rule at its boundaries. Each check asks the lot what
// a ticket would owe at a given moment, without paying.
LLD_TEST(ac_2_1_hourly_rule_charges_each_started_hour_by_vehicle_kind) {
FakePayments payments;
ParkingLot lot(plan, hourly(), payments);
// enter returns an optional Admission. `->ticket` reads the ticket out
// of it; that would be undefined if the car had been refused, but this
// lot is empty, so the test knows there is a spot.
const TicketId car = lot.enter(VehicleKind::car, at(9h))->ticket;
const TicketId bike = lot.enter(VehicleKind::motorcycle, at(9h))->ticket;
LLD_CHECK(lot.amount_due(car, at(9h)) == 250); // a minimum of one hour
LLD_CHECK(lot.amount_due(car, at(10h)) == 250); // exactly one hour
LLD_CHECK(lot.amount_due(car, at(10h) + 1s) == 500); // a second hour started
LLD_CHECK(lot.amount_due(bike, at(10h) + 1s) == 200); // 2 hours x 100
}
// AC-2.2: a flat price for one minute and for fourteen hours alike.
LLD_TEST(ac_2_2_flat_rule_charges_one_price_however_long) {
FakePayments payments;
ParkingLot lot(plan, flat(), payments);
const TicketId van = lot.enter(VehicleKind::van, at(9h))->ticket;
LLD_CHECK(lot.amount_due(van, at(9h) + 1min) == 1'200);
LLD_CHECK(lot.amount_due(van, at(23h)) == 1'200);
}

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

test_step2.cpp
// Four tests of the 15-minute exit window (FR-6, FR-7). Each car enters at
// 09:00 into an empty lot with the hourly rule (2.50 an hour for a car).
// AC-2.4: pays 250 at 09:50, then tries again at 09:55. The second attempt
// is refused as nothing_due, and the fake's record proves the card was
// charged once only.
LLD_TEST(ac_2_4_paying_again_inside_the_window_is_refused_and_not_charged) {
FakePayments payments;
ParkingLot lot(plan, hourly(), payments);
const TicketId car = lot.enter(VehicleKind::car, at(9h))->ticket;
const PayResult first = lot.pay(car, "card", at(9h + 50min));
LLD_CHECK(first.status == PayStatus::paid && first.charged_cents == 250);
LLD_CHECK(lot.pay(car, "card", at(9h + 55min)).status == PayStatus::nothing_due);
LLD_CHECK(payments.charges == std::vector<std::int64_t>{250});
}
// AC-2.5: after the window closes, the ticket owes the fee so far minus
// what it paid, and a second payment adds to the first.
LLD_TEST(ac_2_5_after_the_window_only_the_difference_is_charged) {
FakePayments payments;
ParkingLot lot(plan, hourly(), payments);
const TicketId car = lot.enter(VehicleKind::car, at(9h))->ticket;
// The PayResult is not needed here; the checks below show the effect.
lot.pay(car, "card", at(9h + 50min)); // 1 hour: 250
// At 10:06 the window has closed and a second hour has started.
LLD_CHECK(lot.amount_due(car, at(10h + 6min)) == 250);
const PayResult second = lot.pay(car, "card", at(10h + 6min));
LLD_CHECK(second.status == PayStatus::paid && second.charged_cents == 250);
// The extra brackets are needed: without them, the comma inside the
// braces would split LLD_CHECK's argument in two.
LLD_CHECK(payments.charges == (std::vector<std::int64_t>{250, 250}));
// Both payments count: at 11:30 three hours have started and 500 is paid.
// (750 - 500 = 250. Had the second payment replaced the first, it would
// be 500: this check catches `=` written for `+=`.)
LLD_CHECK(lot.amount_due(car, at(11h + 30min)) == 250);
}
// AC-3.1: the window includes its last second, and the exit frees the
// spot: free regular spots go back to 2, and the next car gets spot 3.
LLD_TEST(ac_3_1_exit_opens_inside_the_window_and_frees_the_spot) {
FakePayments payments;
ParkingLot lot(plan, hourly(), payments);
const TicketId car = lot.enter(VehicleKind::car, at(9h))->ticket;
lot.pay(car, "card", at(9h + 50min));
// Exactly 15 minutes later, and a second hour has started: the window
// still covers it.
LLD_CHECK(lot.exit(car, at(10h + 5min)).status == ExitStatus::opened);
LLD_CHECK_EQ(lot.free_spots(SpotSize::regular), 2);
LLD_CHECK(lot.enter(VehicleKind::car, at(10h + 6min))->spot == SpotId{3});
}
// AC-3.3: two cars both exit 16 minutes after paying, one minute after
// their windows close. Only the one whose stay has entered a new hour owes
// more (250 for the second hour).
LLD_TEST(ac_3_3_late_exit_needs_the_difference_only_if_more_is_due) {
FakePayments payments;
ParkingLot lot(plan, hourly(), payments);
const TicketId early = lot.enter(VehicleKind::car, at(9h))->ticket;
const TicketId late = lot.enter(VehicleKind::car, at(9h))->ticket;
lot.pay(early, "card", at(9h + 10min));
lot.pay(late, "card", at(9h + 50min));
// 16 minutes after paying, still inside the first hour: nothing more is due.
LLD_CHECK(lot.exit(early, at(9h + 26min)).status == ExitStatus::opened);
// 16 minutes after paying, a second hour has started.
const ExitResult refused = lot.exit(late, at(10h + 6min));
LLD_CHECK(refused.status == ExitStatus::payment_needed && refused.due_cents == 250);
}

Failures. A declined card (AC-2.3), an unpaid ticket at the exit (AC-3.2), unknown and used tickets (AC-2.6, AC-3.4), a time before entry, a negative price, and a null rule. The declined-card, unpaid-exit, and unknown- or used-ticket tests check both the answer and that nothing else changed (no charge made, spot still taken); the others check the exception.

Rule changes. One test issues a ticket, switches the rule, issues another, and checks each ticket’s fee (AC-4.1, AC-4.2):

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

test_step2.cpp
// AC-4.1, AC-4.2: two cars enter at the same moment, one before and one
// after set_rule. After an hour they owe different amounts, so each ticket
// is using the rule that was current when it was issued.
// LLD_CHECK_THROWS(expression, type) fails unless the expression throws an
// exception of that type; here, setting a null rule is refused.
LLD_TEST(ac_4_1_and_ac_4_2_a_new_rule_applies_only_to_later_entries) {
FakePayments payments;
ParkingLot lot(plan, hourly(), payments);
const TicketId before = lot.enter(VehicleKind::car, at(9h))->ticket;
lot.set_rule(flat());
const TicketId after = lot.enter(VehicleKind::car, at(9h))->ticket;
LLD_CHECK(lot.amount_due(before, at(10h)) == 250); // hourly, as shown at entry
LLD_CHECK(lot.amount_due(after, at(10h)) == 800); // flat
LLD_CHECK_THROWS(lot.set_rule(nullptr), std::invalid_argument);
}

Invariants. One test runs forty rounds of entries, payments, and exits, then checks INV-1 and INV-2 from outside: free spots plus parked vehicles equals the number of spots, and no parked vehicle can leave without paying.

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

test_step2.cpp
// INV-1 and INV-2, seen from outside, after a busy morning: the free
// spots and the vehicles still parked add up to the number of spots, and
// no vehicle still parked can leave without paying.
LLD_TEST(inv_spots_and_tickets_agree_after_many_operations) {
FakePayments payments;
ParkingLot lot(plan, hourly(), payments);
// The test's own list of vehicles still inside, oldest first.
std::vector<TicketId> parked;
Time now = at(8h);
for (int round = 0; round < 40; ++round) {
now += 7min; // a new arrival every 7 minutes, from 08:07
// round % 3 is 0, 1, 2, 0, ...; static_cast turns it into the
// VehicleKind with that position: motorcycle, car, van, motorcycle, ...
const VehicleKind kind = static_cast<VehicleKind>(round % 3);
// Declares `a` and tests it in one `if`: the body runs only when the
// vehicle was admitted, and `a` exists only inside this statement.
if (const std::optional<Admission> a = lot.enter(kind, now)) parked.push_back(a->ticket);
// Every fourth round, the vehicle that has been inside longest pays
// and leaves 5 minutes later, well inside its window.
if (round % 4 == 3 && !parked.empty()) {
const TicketId leaving = parked.front();
LLD_CHECK(lot.pay(leaving, "card", now).status == PayStatus::paid);
LLD_CHECK(lot.exit(leaving, now + 5min).status == ExitStatus::opened);
parked.erase(parked.begin()); // remove it from the front of the list
}
}
// INV-1: every spot is either free or holds one parked vehicle.
const int free = lot.free_spots(SpotSize::small) + lot.free_spots(SpotSize::regular) +
lot.free_spots(SpotSize::large);
LLD_CHECK_EQ(free + static_cast<int>(parked.size()), static_cast<int>(plan.size()));
// INV-2: none of the vehicles still inside has paid, and every price is
// above zero, so each one must be held at the gate.
for (const TicketId t : parked) {
LLD_CHECK(lot.exit(t, now + 5min).status == ExitStatus::payment_needed);
}
}
How this code works: The invariant test, round by round

The test plays a busy morning against the five-spot plan (spots 1–2 small, 3–4 regular, 5 large) and keeps its own list, parked, of the tickets still inside, oldest first.

  • Every round, 7 minutes pass and one vehicle arrives. The kinds cycle motorcycle, car, van, because round % 3 goes 0, 1, 2, 0, … and the static_cast turns each number into the VehicleKind at that position. A refused vehicle gets no ticket and is not added.
  • Every fourth round (round % 4 == 3, so rounds 3, 7, 11, …) the oldest ticket pays and leaves 5 minutes later. Paying must succeed, because every price is above zero, so something is always due. Leaving must succeed, because 5 minutes is inside the window.

The first eight rounds:

Round Time Arrives Result Leaves parked after
0 08:07 motorcycle ticket 1, spot 1 1
1 08:14 car ticket 2, spot 3 1, 2
2 08:21 van ticket 3, spot 5 1, 2, 3
3 08:28 motorcycle ticket 4, spot 2 ticket 1 (spot 1) 2, 3, 4
4 08:35 car ticket 5, spot 4 2, 3, 4, 5
5 08:42 van refused 2, 3, 4, 5
6 08:49 motorcycle ticket 6, spot 1 2, 3, 4, 5, 6
7 08:56 car refused ticket 2 (spot 3) 3, 4, 5, 6

The car in round 7 is refused before ticket 2 leaves, because in each round the arrival comes first. After 40 rounds the test checks the two invariants from outside. INV-1: the free spots on the three boards plus the length of parked must equal 5. INV-2: every ticket still in parked has never paid, so each one must get payment_needed at the exit.

Did the tests check enough? As a check on the tests themselves, the example was changed by hand in eleven small ways, one at a time: < for <= at the window’s end, = for += when recording a payment, highest floor instead of lowest, and so on. Each time, at least one test should fail. On the first run, three changes went unnoticed: the window boundary, the +=, and the lowest number within a floor. Tests were added for each (the exact-15-minutes exit in ac_3_1, the second payment counted in ac_2_5, and a one-floor plan in step 3), and after that all eleven changes were caught. This is a hand-made version of mutation testing; it found real gaps that line coverage would not.

To run all the tests for this study:

Terminal window
cd examples
cmake --preset gcc-debug
cmake --build --preset gcc-debug
ctest --preset gcc-debug -R cs_parking

Concurrency. The assumption in the scope is that one server handles one request at a time, so ParkingLot has no locks and says “not thread-safe” in its header. If the server instead handled each gate on its own thread, three problems would appear:

  1. Two cars, one spot. enter chooses a spot and then marks it taken. That is check-then-act: two threads can both choose spot 3 before either marks it. One std::mutex in ParkingLot, locked for the whole of each public function, makes each use case happen all at once. At a few requests a second, one lock is enough (not measured).
  2. A slow card provider blocks every gate. charge is a network call. Holding the lock during it would stop both entrances while one driver’s card is checked. But releasing the lock opens a new race: two pay stations could both see 7.50 due and both charge it.
  3. A reference that dangles after the lock is released. If pay released the lock and another thread then admitted a car, tickets_ could reallocate and Ticket& t would point at freed memory.

Problem 1 needs only the lock in enter. A sketch of a pay that handles problems 2 and 3, not part of the example:

IllustrativeA fragment for explanation; not compiled on its own.

// A sketch: mutex_, begin_payment, cancel_payment, and finish_payment do
// not exist in the example. It keeps an index (a number), never a
// reference, across the time the lock is released.
PayResult ParkingLot::pay(TicketId ticket, const std::string& card_token, Time now) {
std::int64_t due = 0;
std::size_t index = 0;
// Part 1, under the lock. The extra braces make a block, so `lock` is
// destroyed at the closing brace and the mutex is released there.
// std::scoped_lock locks the mutex when created and unlocks it when
// destroyed, even if the block is left by an exception.
{
std::scoped_lock lock(mutex_);
// ... look up and check the ticket as before, then:
due = tickets_[index].amount_due(now);
tickets_[index].begin_payment(); // new state: a second pay is refused
}
// Part 2, no lock held: other gates can be served during the slow call.
bool accepted = false;
try {
accepted = payments_.charge(card_token, due); // no lock held
} catch (...) {
// catch (...) catches any exception. Take the lock again, undo the
// "payment in progress" state, then `throw;` passes the same
// exception on to the caller.
std::scoped_lock lock(mutex_);
tickets_[index].cancel_payment(); // as before the call, then report it
throw;
}
// Part 3, under the lock again, until the function returns.
std::scoped_lock lock(mutex_);
Ticket& t = tickets_[index]; // look it up again: tickets_ may have grown
if (!accepted) {
t.cancel_payment();
return {PayStatus::declined};
}
t.finish_payment(due, now);
return {PayStatus::paid, due};
}

The ticket gains a fourth state, “payment in progress”, held while the lock is released. A real provider also needs an idempotency key per attempt, so that a retry after a timeout does not charge twice. See Thread safety and Idempotency and retries.

Persistence. Everything is in memory. If the server restarts, every ticket and every taken spot is forgotten, and drivers cannot leave. A real system writes each ticket and each payment to storage before it opens a gate or reports a payment, and rebuilds ParkingLot from storage at start-up. One consequence for this design: a rule stored in a database must be data (a rule kind and its prices), so the code that loads tickets needs a function that turns that data back into a FeeRule. See Repository and unit of work.

The curriculum’s two changes arrive after the first version is in use. Each is a new step in the example, and each says what moved and what did not. See Design evolution for the general approach.

“We are opening the second level. Each level needs its own board, and we sometimes close a level for cleaning.”

New and changed requirements

  • FR-2 (changed) The smallest size that fits, then the lowest floor, then the lowest spot number, among open floors only.
  • FR-3 (changed) The entrance board counts open floors only.
  • FR-8 Each floor has its own board with its free spots by size, even while it is closed.
  • FR-9 The operator can close and reopen a floor. A closed floor gets no new vehicles; vehicles already there can still pay and leave.
  • UC-5 Close a floor. AC-5.1 After closing, no vehicle is sent to that floor. AC-5.2 A vehicle on a closed floor can still pay and exit.

What moved. Each spot gains a floor number, given in the plan; the car park gains a set of closed floors, three public functions (free_spots(int, SpotSize), close_floor, open_floor), and one private helper, check_floor.

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

parking_lot.hpp
// One spot as the operator describes it. Floors are numbered from 0, the
// ground floor.
// The car park is now built from a list of these, one per spot, in spot
// number order: entry n of the list is spot n. The floors can come in any
// order, and a floor exists simply because some spot names it.
struct SpotPlan {
int floor;
SpotSize size;
};
// What enter hands back to the entrance: the ticket, the spot, and now
// also the floor, copied from the spot's plan entry.
struct Admission {
TicketId ticket;
SpotId spot;
int floor; // so the entrance can say where to drive
};

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

parking_lot.cpp
// FR-2, changed: the smallest size that fits, then the lowest floor,
// then the lowest number, among open floors.
// Only chooses: it changes nothing, which is why it is const. Returns
// std::nullopt if no open floor has a free spot the vehicle fits.
std::optional<SpotId> ParkingLot::choose_spot(VehicleKind vehicle) const {
// As in step 2, the sizes are tried smallest first, so size still wins
// over floor: a free regular spot upstairs beats a large one downstairs.
for (const SpotSize size : {SpotSize::small, SpotSize::regular, SpotSize::large}) {
if (!fits(vehicle, size)) continue;
// The index of the best spot of this size seen so far. It starts
// empty, meaning "none found yet". Spots need not be in floor
// order, so the first free one is not always the answer: the loop
// must look at them all before it knows the lowest floor.
std::optional<std::size_t> best;
for (std::size_t i = 0; i < spots_.size(); ++i) {
const Spot& spot = spots_[i];
// Skip a spot of another size, a taken spot (its optional ticket
// holds a value), or a spot on a closed floor. set::contains is
// C++20 and answers "is this floor in the set?".
if (spot.size != size || spot.ticket || closed_floors_.contains(spot.floor)) continue;
// Keep this spot if it is the first candidate, or on a strictly
// lower floor than the best so far. `<`, not `<=`: on the same
// floor the earlier, lower-numbered spot stays the best.
if (!best || spot.floor < spots_[*best].floor) best = i;
}
// Found one of this size: stop here, without trying larger sizes.
if (best) return SpotId{static_cast<int>(*best) + 1};
}
return std::nullopt;
}
How this code works: Step 3's choose_spot: what changed

In step 2 there were no floors, so the lowest-numbered free spot of a size was the answer. Now a spot’s number says nothing about its floor: the plan can list floor 1 before floor 0. So, for each size, the inner loop looks at every spot and keeps the best one in best:

  1. best starts empty: no candidate yet.
  2. A spot that is the wrong size, taken, or on a closed floor is skipped with continue.
  3. The first spot that survives becomes best. A later one replaces it only if its floor is strictly lower. On the same floor the earlier spot, which has the lower number, stays.
  4. After the loop, if best holds an index, that spot is the answer and the function returns; larger sizes are never tried. If it is still empty, the outer loop moves on to the next size.

A worked example. The first car in the step 3 test, with this plan: spot 1 regular on floor 1, spot 2 regular on floor 0, spot 3 small on floor 1, spot 4 large on floor 0, spot 5 large on floor 1. A car does not fit small, so the outer loop starts at regular:

i Spot Floor Size What happens best after
0 1 1 regular first candidate 0 (spot 1)
1 2 0 regular floor 0 is lower than floor 1 1 (spot 2)
2 3 1 small wrong size, skipped 1
3 4 0 large wrong size, skipped 1
4 5 1 large wrong size, skipped 1

best is index 1, so the car gets spot 2 on the ground floor. The outer loop stops at regular, because it found a spot there, so the large size is never tried, even though large spot 4 is also on the ground floor.

Size still comes first. A car prefers a regular spot upstairs to a large spot on the ground floor, because a van could use only the large one. This was a question for the client, not a decision to make alone: “lowest floor first” would also be a reasonable answer, and it would change one loop.

What did not move. Ticket, the fee rules, Payments, pay, and exit are unchanged; the step 3 tests include one that checks this. There is still no Floor class: a floor has a number, a board computed from the spots, and an open or closed flag. If floors later gain their own prices or their own entrances, that is the time to give them a class.

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

test_step3.cpp
// The `plan` used here is defined earlier in this file, out of floor order
// on purpose: spot 1 regular on floor 1, spot 2 regular on floor 0, spot 3
// small on floor 1, spot 4 large on floor 0, spot 5 large on floor 1.
// FakePayments approves every card token except "declined".
// AC-1.2 (changed): size first, then floor, then number.
LLD_TEST(ac_1_2_changed_size_first_then_lowest_floor_then_lowest_number) {
FakePayments payments;
ParkingLot lot(plan, hourly(), payments);
// Spot 1 is the first regular spot in the list, but spot 2 is on a
// lower floor, so it wins. `first &&` checks the optional holds an
// Admission before `->` reads from it; `&&` stops at the first false.
const std::optional<Admission> first = lot.enter(VehicleKind::car, at(9h));
LLD_CHECK(first && first->spot == SpotId{2} && first->floor == 0);
// The ground floor has no regular spot left; a car still prefers a
// regular spot upstairs to the large one on the ground floor.
const std::optional<Admission> second = lot.enter(VehicleKind::car, at(9h));
LLD_CHECK(second && second->spot == SpotId{1} && second->floor == 1);
// A van fits only large spots: spot 4, ground floor, beats spot 5.
LLD_CHECK(lot.enter(VehicleKind::van, at(9h))->spot == SpotId{4});
}
// Two regular spots on the same floor: the lower number wins. The test
// above cannot show this (no floor there has two free spots of one size),
// so a deliberate change to the order within a floor went unnoticed until
// this test was added.
LLD_TEST(ac_1_2_changed_on_one_floor_the_lowest_number_wins) {
FakePayments payments;
ParkingLot lot({{0, SpotSize::regular}, {0, SpotSize::regular}}, hourly(), payments);
LLD_CHECK(lot.enter(VehicleKind::car, at(9h))->spot == SpotId{1});
}
// AC-5.1: with the ground floor closed, cars go upstairs, first to regular
// spot 1, then to large spot 5, and a third car is refused although spots
// 2 and 4 are free. The two boards disagree on purpose: the entrance counts
// open floors only, a floor's own board counts its spots even while closed.
// Reopening the floor makes spot 2 available again.
LLD_TEST(ac_5_1_a_closed_floor_gets_no_new_vehicles) {
FakePayments payments;
ParkingLot lot(plan, hourly(), payments);
lot.close_floor(0);
LLD_CHECK(lot.enter(VehicleKind::car, at(9h))->spot == SpotId{1});
LLD_CHECK(lot.enter(VehicleKind::car, at(9h))->spot == SpotId{5});
// has_value() is false for an empty optional: the car was refused.
LLD_CHECK(!lot.enter(VehicleKind::car, at(9h)).has_value());
LLD_CHECK_EQ(lot.free_spots(SpotSize::regular), 0); // entrance: open floors
LLD_CHECK_EQ(lot.free_spots(0, SpotSize::regular), 1); // the closed floor's own board
lot.open_floor(0);
LLD_CHECK(lot.enter(VehicleKind::car, at(9h))->spot == SpotId{2});
}
// AC-5.2: a car parked on the ground floor before it closes can still pay
// and leave, and its spot shows as free on that floor's board afterwards.
LLD_TEST(ac_5_2_vehicles_on_a_closed_floor_can_still_leave) {
FakePayments payments;
ParkingLot lot(plan, hourly(), payments);
// `*` copies the Admission out of the optional (safe: the lot is empty).
const Admission a = *lot.enter(VehicleKind::car, at(9h));
LLD_CHECK_EQ(a.floor, 0);
lot.close_floor(0);
LLD_CHECK(lot.pay(a.ticket, "card", at(10h)).status == PayStatus::paid);
LLD_CHECK(lot.exit(a.ticket, at(10h + 5min)).status == ExitStatus::opened);
LLD_CHECK_EQ(lot.free_spots(0, SpotSize::regular), 1);
}

“Some spots now have chargers. Drivers ask for one at the entrance. Charging costs extra per hour, and the receipt must show parking and charging separately.”

New and changed requirements

  • FR-10 Some spots have a charger. A driver who asks to charge gets the smallest charger spot that fits, on the lowest open floor; if none is free, an ordinary spot and no charging. A driver who does not ask gets an ordinary spot first, and a charger spot of the same size only when no ordinary spot of that size is free.
  • FR-11 Charging costs a price per started hour, set by the operator and fixed at entry, like the fee rule. The fee shows parking and charging separately.
  • AC-1.5 A driver who asks to charge gets a charger spot.
  • AC-1.6 Other drivers get ordinary spots first, but are not turned away while a charger spot that fits is free.
  • AC-1.7 If no charger spot is free, the driver gets an ordinary spot and is not charged for charging.
  • AC-2.7 Charging is billed per started hour of the whole stay, not for the time the battery takes, and shown separately.
  • AC-4.3 The charging price is the one in force at entry.

What moved.

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

parking_lot.hpp
// One spot as the operator describes it. Floors are numbered from 0, the
// ground floor.
struct SpotPlan {
int floor;
SpotSize size;
// A default member value: a plan entry written as {0, SpotSize::large}
// leaves out the third value and gets `false`, an ordinary spot.
bool charger = false; // added in change 2; older plans still compile
};
// What the driver asks for at the entrance (FR-10). An enum, not a bool,
// so a call reads enter(kind, now, Charging::wanted).
enum class Charging { not_needed, wanted };
// What enter hands back. `charging` is true only when the driver asked to
// charge and the chosen spot has a charger; a driver who did not ask, but
// was sent to a charger spot because no ordinary one was free, gets false.
struct Admission {
TicketId ticket;
SpotId spot;
int floor; // so the entrance can say where to drive
bool charging = false; // false if the driver wanted a charger and none was free
};
  • SpotPlan gains bool charger = false, so every plan written for step 3 still compiles and behaves as before.
  • enter gains a Charging argument with a default. It is an enum, not a bool: enter(kind, now, Charging::wanted) says what it means; enter(kind, now, true) does not.
  • Admission says whether the driver got a charger, because a driver who asked may not have.
  • The ticket gains a charging price per hour (0 for no charging) and a fee function that returns the two parts:

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

ticket.hpp
// The fee for a stay so far, in two parts, so the pay station can show
// them on separate lines (FR-11).
// A plain value with no rules of its own: Ticket::fee fills it in and the
// caller reads it. amount_due uses total_cents() in place of the step 2
// single fee, so the window and payment rules work on the sum.
struct Fee {
std::int64_t parking_cents = 0; // from the ticket's fee rule
std::int64_t charging_cents = 0; // 0 for a ticket that does not charge
std::int64_t total_cents() const { return parking_cents + charging_cents; }
};

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

ticket.cpp
// The fee for the whole stay up to `now`, in its two parts. Ignores what has
// been paid and the exit window; amount_due deals with those. Throws
// std::invalid_argument if now is before entry.
Fee Ticket::fee(Time now) const {
if (now < entered_) throw std::invalid_argument("time is before entry");
const std::chrono::seconds stay = now - entered_;
// The first value fills parking_cents and the second charging_cents, in
// the order Fee declares them. Parking is the shared rule, as before.
// Charging uses the same started_hours as the hourly rule (whole stay,
// minimum one hour) times the price fixed when the ticket was issued;
// a ticket that does not charge has a price of 0, so its part is 0.
return Fee{rule_->fee_cents(vehicle_, stay),
started_hours(stay) * charging_cents_per_hour_};
}

amount_due now subtracts what was paid from fee(now).total_cents(); the window, may_pay, may_exit, pay, and exit are unchanged.

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

parking_lot.cpp
// The free spot of this size and kind on the lowest open floor, lowest
// number first.
// This is the inner loop of step 3's choose_spot, moved into a helper with
// one more filter: the spot must be a charger spot if `charger` is true and
// an ordinary spot if it is false. Returns std::nullopt if none is free.
std::optional<SpotId> ParkingLot::best_spot(SpotSize size, bool charger) const {
std::optional<std::size_t> best; // empty until a candidate is found
for (std::size_t i = 0; i < spots_.size(); ++i) {
const Spot& spot = spots_[i];
// Skip the wrong size, the wrong kind of spot, a taken spot, or a
// spot on a closed floor.
if (spot.size != size || spot.charger != charger || spot.ticket ||
closed_floors_.contains(spot.floor)) {
continue;
}
// Strictly lower floor only, so on one floor the lowest number stays.
if (!best || spot.floor < spots_[*best].floor) best = i;
}
if (!best) return std::nullopt;
return SpotId{static_cast<int>(*best) + 1};
}
// FR-10: a driver who wants to charge gets the smallest charger spot that
// fits, if any is free. Otherwise FR-2 as before, with an ordinary spot
// before a charger spot of the same size, so chargers stay free for those
// who want them but a size never goes to waste.
// Only chooses; enter decides whether the ticket is billed for charging.
std::optional<SpotId> ParkingLot::choose_spot(VehicleKind vehicle, Charging charging) const {
// The three sizes, smallest first, written once and used by both loops.
constexpr SpotSize sizes[] = {SpotSize::small, SpotSize::regular, SpotSize::large};
// Pass 1, only for a driver who wants to charge: charger spots only,
// smallest fitting size first. A charger spot of any fitting size beats
// an ordinary spot.
if (charging == Charging::wanted) {
for (const SpotSize size : sizes) {
if (!fits(vehicle, size)) continue;
// Declare and test in one `if`: return the spot as soon as one
// is found; otherwise try the next size.
if (const std::optional<SpotId> spot = best_spot(size, true)) return spot;
}
}
// Pass 2, for everyone else, and for a charging driver when no charger
// spot was free (AC-1.7): size first, as in step 3, and within each
// size an ordinary spot (false) before a charger spot (true).
for (const SpotSize size : sizes) {
if (!fits(vehicle, size)) continue;
for (const bool charger : {false, true}) {
if (const std::optional<SpotId> spot = best_spot(size, charger)) return spot;
}
}
return std::nullopt;
}
How this code works: Step 4's choose_spot: two passes

Step 3’s inner loop has moved into best_spot(size, charger), which finds the best free spot of one size and one kind (charger or ordinary) on the lowest open floor. choose_spot now just decides the order in which to ask it:

  1. Pass 1, only if the driver wants to charge. Ask for a charger spot of each fitting size, smallest first. The first answer wins.
  2. Pass 2, for everyone else, and for a charging driver who found no charger. For each fitting size, smallest first, ask for an ordinary spot, then a charger spot of the same size.
  3. Nothing found in either pass: std::nullopt, and the vehicle is refused.

choose_spot does not decide whether the driver is billed for charging. enter does that afterwards: charging is billed only if the driver asked and the chosen spot has a charger.

Worked examples from the step 4 tests. The plan: spot 1 regular, spot 2 regular with a charger, and spot 4 large on floor 0; spot 3 regular with a charger and spot 5 large with a charger on floor 1. Each row is one car.

Test Before it arrives Wants to charge? Pass that answers Spot Billed for charging?
ac_1_5, first car empty lot yes 1: regular charger, lowest floor 2 yes
ac_1_5, second car spot 2 taken yes 1: regular charger, floor 1 3 yes
ac_1_6, first car empty lot no 2: ordinary regular 1 no
ac_1_6, second car spot 1 taken no 2: no ordinary regular, so charger 2 no
ac_1_7, second car floor 1 closed, spot 2 taken yes 1 finds nothing; 2: ordinary regular 1 no

In the ac_1_6 row, large spot 4 is free but is not chosen: pass 2 finishes the regular size, charger spots included, before it looks at large. That is the trade-off below.

What did not move, and two tempting wrong turns.

  • VehicleKind is unchanged. An electric car is a car that wants to charge, not a fourth kind of vehicle: it fits the same spots and pays the same parking price. Adding ev_car would add a row to the fit table and a price to every Prices, and it still would not say whether this driver wants to charge today.
  • Charging is not a decorator around FeeRule. A decorator would add the charging cost into one number, but FR-11 asks for two lines on the receipt, and charging applies only to some tickets, while one rule object is shared by every ticket issued under it. The Fee struct keeps the two parts apart.
  • HourlyRule, FlatRule, Payments, the exit window, and the floor functions are unchanged. The step 4 tests check what changed, plus plans_without_chargers_behave_as_in_step_3, which checks that a plan with no chargers gets the step 3 behaviour.

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

test_step4.cpp
// The `plan` here, defined earlier in this file: spot 1 regular (floor 0),
// spot 2 regular with charger (floor 0), spot 3 regular with charger
// (floor 1), spot 4 large (floor 0), spot 5 large with charger (floor 1).
// Every car enters at 08:00 into an empty lot with the hourly rule.
// AC-1.5: two drivers who want to charge get the two regular charger spots,
// ground floor first, even though ordinary spot 1 is free.
LLD_TEST(ac_1_5_a_driver_who_wants_to_charge_gets_a_charger_spot) {
FakePayments payments;
ParkingLot lot(plan, hourly(), payments);
const Admission a = *lot.enter(VehicleKind::car, at(8h), Charging::wanted);
LLD_CHECK(a.spot == SpotId{2} && a.charging);
// The next one goes upstairs rather than to an ordinary spot.
const Admission b = *lot.enter(VehicleKind::car, at(8h), Charging::wanted);
LLD_CHECK(b.spot == SpotId{3} && b.charging);
}
// AC-1.6: a car that does not charge gets ordinary spot 1. The next one
// gets charger spot 2 rather than large spot 4 (size before charger), and
// is not billed for charging.
LLD_TEST(ac_1_6_other_drivers_get_ordinary_spots_first_but_are_not_turned_away) {
FakePayments payments;
ParkingLot lot(plan, hourly(), payments);
LLD_CHECK(lot.enter(VehicleKind::car, at(8h))->spot == SpotId{1});
// No ordinary regular spot is left: a charger spot of the right size
// comes before a large spot, and the car does not charge.
const Admission b = *lot.enter(VehicleKind::car, at(8h));
LLD_CHECK(b.spot == SpotId{2} && !b.charging);
}
// AC-1.7: with floor 1 closed, spot 2 is the only charger spot open. The
// second driver who wants to charge falls through to pass 2 and gets
// ordinary spot 1, with charging false.
LLD_TEST(ac_1_7_no_charger_free_means_an_ordinary_spot_and_no_charging) {
FakePayments payments;
ParkingLot lot(plan, hourly(), payments);
lot.close_floor(1);
lot.enter(VehicleKind::car, at(8h), Charging::wanted); // spot 2
const Admission b = *lot.enter(VehicleKind::car, at(8h), Charging::wanted);
LLD_CHECK(b.spot == SpotId{1} && !b.charging);
}
// AC-2.7: 08:00 to 10:30 is 3 started hours, so parking is 3 x 250 = 750
// and charging 3 x 150 = 450. The charging car owes and is charged 1'200;
// the car beside it, which did not ask to charge, owes only 750.
LLD_TEST(ac_2_7_charging_is_billed_per_started_hour_and_shown_separately) {
FakePayments payments;
ParkingLot lot(plan, hourly(), payments);
lot.set_charging_price(150);
const TicketId ev = lot.enter(VehicleKind::car, at(8h), Charging::wanted)->ticket;
const TicketId plain = lot.enter(VehicleKind::car, at(8h))->ticket;
const std::optional<Fee> fee = lot.fee(ev, at(10h + 30min));
LLD_CHECK(fee && fee->parking_cents == 750 && fee->charging_cents == 450);
LLD_CHECK(lot.amount_due(ev, at(10h + 30min)) == 1'200);
LLD_CHECK(lot.amount_due(plain, at(10h + 30min)) == 750);
LLD_CHECK(lot.pay(ev, "card", at(10h + 30min)).charged_cents == 1'200);
}
// AC-4.3: as with the fee rule, the price in force at entry is used: it is
// copied into the ticket, so changing it later affects later entries only. One hour at
// 150, one hour at 200. A negative price is refused with an exception.
LLD_TEST(ac_4_3_the_charging_price_is_the_one_shown_at_entry) {
FakePayments payments;
ParkingLot lot(plan, hourly(), payments);
lot.set_charging_price(150);
const TicketId before = lot.enter(VehicleKind::car, at(8h), Charging::wanted)->ticket;
lot.set_charging_price(200);
const TicketId after = lot.enter(VehicleKind::car, at(8h), Charging::wanted)->ticket;
LLD_CHECK(lot.fee(before, at(9h))->charging_cents == 150);
LLD_CHECK(lot.fee(after, at(9h))->charging_cents == 200);
LLD_CHECK_THROWS(lot.set_charging_price(-1), std::invalid_argument);
}

The step 4 demo has two floors, two charger spots, and a floor closed for cleaning:

Expected output
08:00 car (wants to charge) enters: ticket 1, floor 0, spot 2, charging
08:05 car enters: ticket 2, floor 0, spot 1
08:10 car enters: ticket 3, floor 1, spot 3
08:15 car enters: ticket 4, floor 1, spot 4
08:20 van enters: ticket 5, floor 1, spot 5
09:00 floor 1 closed for cleaning
09:00 ticket 2: parking 2.50; paid 2.50; gate opens
floor 0 board: regular 1, large 0
floor 1 board: regular 0, large 0
entrance board: regular 1, large 0
09:10 car (wants to charge) enters: ticket 6, floor 0, spot 1
10:30 ticket 1: parking 7.50, charging 4.50; paid 12.00; gate opens
10:35 ticket 4: parking 7.50; paid 7.50; gate opens
floor 0 board: regular 1, large 0
floor 1 board: regular 1, large 0
entrance board: regular 1, large 0

At 09:10 a driver wants to charge, but both charger spots are taken (spot 2 by ticket 1, and spot 4, on the closed floor, by ticket 4), so they get spot 1 without charging (AC-1.7). At 10:30 ticket 1 has stayed 2 h 30 min: 3 started hours of parking (7.50) and of charging at 1.50 (4.50), shown separately (AC-2.7). At 10:35 ticket 4 leaves from the closed floor (AC-5.2); it parked in a charger spot but did not ask to charge, so it pays parking only.

In a 45-minute interview you will not write all of this. A plan that fits the time boxes from The design workflow:

Time What to do What to say
About 5 min Ask about vehicle and spot sizes, the bigger-spot rule, the fee rules, which price applies after a change, payment, and the exit window. Write FR-1 … FR-7 and an out-of-scope list. “The answer to ‘which price applies’ decides whether tickets carry their rule.”
3–5 min Sketch ParkingLot, Ticket, FeeRule, Payments. Say what is not a class: vehicle, floor, gate. “Vehicle is an enum: nothing about a vehicle varies except one row in a table.”
10–15 min Outline Ticket and ParkingLot with members and owners; write the FeeRule interface; state INV-1 and INV-4. “Each ticket shares the rule in force at entry, so changing the price cannot change a parked car’s fee.”
10–15 min Write choose_spot, Ticket::amount_due, and ParkingLot::pay; trace one car from entry to exit, including a declined card. “The card is charged before anything is recorded, so a declined card changes nothing.”
About 5 min Take one change, usually floors or chargers, and say what moves. “Floors are a number on each spot; the ticket and fee rules do not change.”

What is usually expected at each level

Level Usually expected
Junior Asks about vehicles, sizes, and fees; produces a small set of classes with clear names; writes a working allocation; computes an hourly fee with the started-hour boundary right; handles a full car park.
Mid-level All of the above, plus: places each rule in the class that owns its data; justifies Strategy by a requirement rather than by habit; handles the declined card, the used ticket, and the exit window; names tests by AC.
Senior All of the above, plus: explains the ownership and lifetime of the shared rule; raises the check-then-act race and the slow card call without being asked; says what persistence would need; resists extra classes and patterns, and explains which change would justify them.

These are this site’s judgement of common practice, as on How to approach a case study, not any company’s rubric.

This is a teaching design. A real car park would need much more.

  • It is not a financial system. There are no receipts, refunds, tax, currencies, or reconciliation with the card provider. Card handling is a single function on a stand-in; real card data has legal and security rules that this example does not touch.
  • Nothing is stored. A restart loses every ticket; see persistence.
  • Tickets are never removed. tickets_ grows by every vehicle that ever entered, and each old ticket keeps its fee rule alive. For a few thousand tickets a day that is fine for a long time, but a real system would archive tickets after exit, at the cost of the “already used” check needing the archive.
  • One thread. See concurrency.
  • The clock is trusted. Every time comes from the caller. A gate whose clock is wrong could let a driver out free or keep one in. A pay station whose clock is behind the entrance’s would pass a time before entry, and pay or exit would throw std::invalid_argument at a driver; a real system uses one server clock.
  • Hardware fails. A gate that does not open after exit returned opened leaves the ticket closed and the driver stuck; a real system needs an attendant override and an audit log of who used it.
  • Lost tickets, reservations, passes, and licence-plate cameras were out of scope, and each would add requirements and classes.
  • The operator is not authenticated. Anyone who can call set_rule can change the prices.

Each row links a requirement to the design element, the code, and the tests that check it. Step numbers are the example’s steps. See Traceability.

Requirement Design element Code Tests Status
FR-1 which vehicle fits which spot fits table next to the enums spot.hpp fits fits_matches_the_table_for_all_nine_pairs Tested
FR-2 allocation order ParkingLot::choose_spot step 1 park; step 2 choose_spot ac_1_2_smallest_fitting_size_then_lowest_number (step 1); ac_1_3_… (steps 1 and 2); FR-2 changed: ac_1_2_changed_… (step 3) Tested
FR-3 entrance board counts computed from spots_ free_spots(SpotSize) ac_1_4_free_counts_follow_parking_and_leaving (step 1); FR-3 changed: ac_5_1_a_closed_floor_gets_no_new_vehicles (step 3) Tested
FR-4 ticket keeps the rule at entry Ticket::rule_, shared ParkingLot::enter, set_rule ac_4_1_and_ac_4_2_a_new_rule_applies_only_to_later_entries Tested
FR-5 hourly and flat rules FeeRule, HourlyRule, FlatRule fees.hpp, fees.cpp ac_2_1_…, ac_2_2_…, started_hours_rounds_up_with_a_minimum_of_one Tested
FR-6 pay by card, the difference only ParkingLot::pay, Ticket::record_payment parking_lot.cpp pay; ticket.cpp ac_2_3_…, ac_2_4_…, ac_2_5_…, ac_2_6_and_ac_3_4_… Tested
FR-7 exit when nothing is due Ticket::may_exit, exit_window ticket.cpp amount_due; parking_lot.cpp exit ac_3_1_…, ac_3_2_…, ac_3_3_…, a_price_of_zero_needs_no_visit_to_the_pay_station Tested
FR-8 per-floor boards free_spots(int floor, SpotSize) step 3 parking_lot.cpp per_floor_counts_and_unknown_floors Tested
FR-9 close a floor closed_floors_, close_floor, open_floor step 3 parking_lot.cpp ac_5_1_…, ac_5_2_…, closing_a_floor_twice_and_opening_an_open_floor_are_harmless Tested
FR-10 charger spots SpotPlan::charger, Charging, best_spot step 4 choose_spot ac_1_5_…, ac_1_6_…, ac_1_7_…, a_van_can_still_use_a_large_charger_spot Tested
FR-11 charging price, shown separately Fee, Ticket::fee, set_charging_price step 4 ticket.cpp ac_2_7_…, ac_4_3_…, a_late_exit_includes_the_extra_charging_hour Tested
NFR-1 about 2,000 spots, answers at once linear scans in memory choose_spot, free_spots none Not measured
NFR-2 exact cents std::int64_t cents everywhere all money members every fee test compares exact cents Tested
NFR-3 testable without devices Payments interface; time passed in payments.hpp; every Time now argument all tests use FakePayments and fixed times Tested
NFR-4 a new rule changes no other class FeeRule interface fees.hpp none: a design property; see the exercise Reviewed
INV-1, INV-2 spots and tickets agree Spot::ticket by ID; counts from spots enter, exit, free_spots inv_spots_and_tickets_agree_after_many_operations Tested
INV-3 a ticket’s spot fits choose_spot uses fits choose_spot ac_1_3_no_fitting_spot_means_no_entry_even_if_others_are_free Tested
INV-4 never a negative amount due check in Ticket::amount_due ticket.cpp none: only a rule that breaks its contract can reach it Not tested

The last row is honest about a gap: no rule in the example breaks its contract, so the check is never reached. A test could add a deliberately broken rule; see the exercise.

Exercise: A daily cap, and a rule that breaks its contract

The client asks for a third rule: hourly, but never more than a cap per 24 hours. A car at 2.50 an hour with a 20.00 cap pays 20.00 for a day, and for 25 hours pays 20.00 plus one more hour, 22.50.

  1. Which classes change, and which do not? Check your answer against NFR-4.
  2. Write the formula for the fee, and check it at exactly 24 hours. Does your formula charge an extra hour there?
  3. Does your rule keep FeeRule’s contract that a longer stay never costs less? Check just before and just after 24 hours.
  4. Write a test for INV-4: a rule whose fee goes down after an hour, a payment, and then an amount_due call after the window. What should happen?
Show the explained answer

1. One new class, CappedHourlyRule, implementing FeeRule, holding the hourly Prices and the cap Prices. ParkingLot, Ticket, the other rules, and every test stay as they are; only the code that builds rules (in the demo, main) learns the new name. That is NFR-4.

2. Split the stay into whole days and the rest. Each whole day costs the cap. The rest costs its started hours at the hourly price, but no more than the cap. The trap is the minimum of one hour: started_hours returns 1 for a zero-length rest, so a stay of exactly 24 hours would cost the cap plus one hour. Charge nothing for a zero rest when at least one whole day has passed:

IllustrativeA fragment for explanation; not compiled on its own.

// cap_ and per_hour_ are the rule's two Prices: the most a whole day can
// cost, and the price per started hour.
std::int64_t CappedHourlyRule::fee_cents(VehicleKind vehicle,
std::chrono::seconds stay) const {
using namespace std::chrono_literals;
if (stay < 0s) throw std::invalid_argument("stay is negative");
// Dividing one duration by another gives a plain number: how many whole
// 24-hour days fit in the stay (rounded down).
const std::int64_t days = stay / 24h;
// What is left after the whole days, from 0 up to just under 24 hours.
const std::chrono::seconds rest = stay - days * 24h;
const std::int64_t cap = cap_.for_vehicle(vehicle);
// A zero rest after at least one whole day costs nothing; otherwise the
// rest's started hours, but never more than the cap. A stay of 0
// seconds has no whole day, so it still costs the one-hour minimum.
const std::int64_t rest_fee =
(rest == 0s && days > 0)
? 0
: std::min(started_hours(rest) * per_hour_.for_vehicle(vehicle), cap);
return days * cap + rest_fee;
}

At exactly 24 hours: one day, a zero rest, so 2,000 cents. At 25 hours: 2,000 + 250 = 2,250.

3. Yes. One second before 24 hours, the fee is at most the cap. At 24 hours it is exactly the cap. One second after, it is the cap plus at least one hour. Within a day the rest’s fee only grows until it reaches the cap. Checking this matters: a rule that broke the contract would make INV-4’s check throw for a driver who paid early.

4. A test rule that returns 500 for the first hour and 100 after it. A car enters at 09:00 and pays 500 at 09:30. At 11:00, after the window, the fee is 100 and paid is 500. amount_due must throw std::logic_error rather than return −400. The test is LLD_CHECK_THROWS(lot.amount_due(t, at(11h)), std::logic_error), and it would move INV-4’s row in the traceability table from “Not tested” to “Tested”.

  • A few questions turned “design a parking lot” into seven functional requirements. The most important answer was that the price shown at entry applies, which is why each ticket shares its own fee rule.
  • Vehicles and spot sizes are enums with one table function. There are no Vehicle, Floor, Gate, or Singleton classes, because nothing in the requirements needed them.
  • ParkingLot orchestrates; Ticket owns its payment and exit rules; FeeRule only computes a price; Payments is outside, behind an interface.
  • std::shared_ptr<const FeeRule> is justified: several owners for different lengths of time, and an object nobody can change once shared.
  • Expected outcomes (full, declined, unpaid) are returned as values; programming mistakes throw.
  • Spots and tickets refer to each other by ID, so a growing vector cannot leave a dangling pointer.
  • Floors and chargers changed allocation and the ticket’s fee, but not the fee rules, payment, or exit. The tests, named by acceptance criterion, showed what still held.