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
API and data
The contract first, then the data that serves it.
Class API
The public surface, and nothing more
| Call | Answers | Refuses with | Cost |
|---|---|---|---|
ParkingLot(spots, pricing, payments, now) | A lot | Duplicate space ids, if you check | O(n) |
enter(vehicle) | Ticket, or nothing when full for this vehicle | AlreadyInside | O(1) |
leave(ticket_id) | Receipt | UnknownTicket, PaymentDeclined | O(1) plus the card |
free() | Counts by size | Never | O(1) |
Pricing.price_cents(ticket, left_at) | Whole cents, zero or more | Never | O(1) |
Payments.charge(key, cents) | Nothing | PaymentDeclined; may time out | Seconds |
Why it looks like this
- 1
Two verbs
No
findSpotin public. If a gate can find without taking, somebody will build the race on top. - 2
Nothing for full
A caller cannot forget an optional as easily as an exception. And it is not exceptional.
- 3
No
isFull()Full for whom? And the answer is old when it arrives.
free()is for signs. - 4
A ticket id, not a ticket, for leave
The caller may hold an old copy. The lot looks up its own.
What should enter return when the lot is full?
BreaksA ticket with no space
- How
ticket.spot = null.- Limit
- Every caller must remember to look. One forgets.
- Choose when
- Never.
WorksAn exception
- How
LotFull.- Limit
- Saturdays are made of exceptions, and the stack trace costs more than the claim.
- Choose when
- If the language has no good optional.
StrongAn optional, or a result with a reason
- How
Ticket?, orFull(size),AlreadyInside.- Limit
- One more type if you want reasons.
- Choose when
- Here.