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
Verify
Trace it with real values
The point: do not say "done". Put five vehicles through your code, line by line, and write the state after each call.
Trace
The seaside day
Start: S1, M1, M2, M3, L1. Rates 100, 200, 500 cents an hour
| Call | Claim | Small | Medium | Large | Active | Returns |
|---|---|---|---|---|---|---|
| start | S1 | M1 M2 M3 | L1 | none | ||
| 09:00 enter RED-1, car | starts at medium | S1 | M2 M3 | L1 | 1 | ticket 1, M1 |
| 09:00 enter MOTO-1 | small | empty | M2 M3 | L1 | 1 2 | ticket 2, S1 |
| 09:00 enter BUS-1 | large | empty | M2 M3 | empty | 1 2 3 | ticket 3, L1 |
| 09:00 enter MOTO-2 | small empty, medium | empty | M3 | empty | 1 2 3 4 | ticket 4, M2 |
| 09:00 enter BUS-2 | large empty | empty | M3 | empty | 1 2 3 4 | nothing |
| 09:05 enter BLUE-1, car | medium | empty | empty | empty | 1 to 5 | ticket 5, M3 |
| 09:06 enter GREEN-1, car | nothing left | empty | empty | empty | 1 to 5 | nothing |
| 11:10 leave 1 | empty | M1 | empty | 2 to 5 | 600 cents | |
| 11:11 enter GREEN-1, car | medium | empty | empty | empty | 2 to 6 | ticket 6, M1 |
Edges
Small inputs that break large designs
| Input | Expected | Where it is decided |
|---|---|---|
| Leave in the same second | 1 hour, 200 cents | max(1, ...) |
| Leave after exactly 60 minutes | 1 hour | (3600 + 3599) // 3600 = 1 |
| Leave after 60 minutes and 1 second | 2 hours | (3601 + 3599) // 3600 = 2 |
| Leave with ticket 1 again | UnknownTicket | pop returned nothing |
| Enter RED-1 while it is inside | AlreadyInside | inside |
| Card declined, then paid | First an error, then a receipt, one charge | except puts the ticket back |
| Enter RED-1 after it left | A new ticket | inside.discard |
| A lot without spaces | Nothing for everybody | Three empty queues |
first = lot.enter(Vehicle("A", VehicleType.CAR))cards.declines = 1try: lot.leave(first.id)except PaymentDeclined: passbefore = lot.free()[SpotSize.MEDIUM] # still taken: not released before paymentreceipt = lot.leave(first.id) # the ticket was put back, so this worksassert lot.free()[SpotSize.MEDIUM] == before + 1assert cards.charged[f"ticket-{first.id}"] == receipt.cents == 200Invariants
Four sentences that are true after every call
- 1
Nothing is lost
Free spaces plus spaces on tickets is the number of spaces. (During a payment the ticket is in the hands of
leave.) - 2
Nothing is doubled
No two active tickets name the same space or the same plate.
- 3
It fits
On every ticket, the size of the space is at least the smallest size of the vehicle.
- 4
Money and spaces agree
Every space that came back has exactly one successful charge.
The question to ask at each line of leave