Design a parking lot
medium 90 minModel a car park with several levels as classes: vehicles, spaces of different sizes, tickets and a replaceable price rule.
Watch lesson4:48
Pricing strategy
Rules that can be swapped and stacked
The point: "several ways to calculate one thing" is the sentence that asks for Strategy. Keep each rule small, and stack them instead of making one class for each combination.
Strategy
Three rules, one question
| Rule | For | 130 minutes, medium |
|---|---|---|
| Hourly, every started hour | Ordinary days | 3 x 200 = 600 cents |
| Flat | Match days, airports by the day | 1500 cents |
| Weekend at 1.5 times | Saturday and Sunday | 600 x 1.5 = 900 cents |
| First 15 minutes free, then hourly | Dropping somebody off | 600 cents; after 14 minutes 0 |
| At most 2000 cents a day | Long stays | 600 cents; after 12 hours 2000 |
Python
from dataclasses import dataclass, replacefrom datetime import datetime, timedelta, timezone@dataclass(frozen=True)class Stay: size: str entered_at: datetimeclass Hourly: def __init__(self, cents: dict[str, int]) -> None: self._cents = cents def price_cents(self, stay: Stay, left_at: datetime) -> int: seconds = int((left_at - stay.entered_at).total_seconds()) return max(1, (seconds + 3599) // 3600) * self._cents[stay.size]class FirstMinutesFree: """Wraps another rule: the open/closed principle with two lines.""" def __init__(self, minutes: int, inner) -> None: self._limit, self._inner = timedelta(minutes=minutes), inner def price_cents(self, stay: Stay, left_at: datetime) -> int: if left_at - stay.entered_at <= self._limit: return 0 return self._inner.price_cents(stay, left_at)class DailyCap: """No day costs more than the cap. A day is 24 hours from entry.""" def __init__(self, cap_cents: int, inner) -> None: self._cap, self._inner = cap_cents, inner def price_cents(self, stay: Stay, left_at: datetime) -> int: days, rest = divmod(left_at - stay.entered_at, timedelta(days=1)) total = days * self._cap if rest: last_day = replace(stay, entered_at=left_at - rest) total += min(self._cap, self._inner.price_cents(last_day, left_at)) return totalrule = FirstMinutesFree(15, DailyCap(2000, Hourly({"M": 200})))start = datetime(2026, 7, 4, 9, tzinfo=timezone.utc)for hours in (0.25, 2.1667, 12, 24, 49.5): print(hours, rule.price_cents(Stay("M", start), start + timedelta(hours=hours)))Mistakes
Five bugs in a fee method
| Code | Problem | Instead |
|---|---|---|
Duration.between(a, b).toHours() | Rounds down: 119 minutes are 1 hour | Round up from seconds |
3.5 * hourlyRate | Is it per hour or per started hour? 3.5 x 400 = 1400, or 4 x 400 = 1600 | Ask, then write it into the test |
double price | 0.1 + 0.2 is not 0.3 | Whole cents |
price * 1.5 for weekends | A fraction of a cent, and a float | (cents * 15000 + 5000) // 10000: basis points, rounded half up |
| "Is the exit on a weekend?" | Friday 23:00 to Saturday 01:00 pays the weekend for all | Price each hour by its own day: next page |
Swap
Changing the rule while cars are inside
Marketing changes the price at noon. Who pays what?
BreakssetPricing(newRule) on the running lot
- How
- A field that any thread may replace.
- Limit
- Someone who came at 9 for 200 an hour pays 400. Two threads in one
leavemay use two rules. - Choose when
- Never without a lock, and not for people who saw the old sign.
WorksThe rule at exit decides
- How
- Restart, or an atomic swap, with the new rule.
- Limit
- Legal in some places, a surprise in all.
- Choose when
- If the sign says prices at time of exit.
StrongThe tariff at entry decides
- How
- The ticket carries the tariff id.
Tariffs.get(id)returns a rule that never changes; a new price is a new id. - Limit
- Old tariffs must be kept while anyone is inside.
- Choose when
- Nearly always. The price the driver saw is the price they pay.
Test
Why this is easy to test
A rule is a function of its arguments. No clock, no database, no lot. A table of stays and expected cents is the test, and the same table can go to the people who set the prices.
Where the rule comes from