AlgoViz

Design a parking lot

medium 90 min

Model 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

CallAnswersRefuses withCost
ParkingLot(spots, pricing, payments, now)A lotDuplicate space ids, if you checkO(n)
enter(vehicle)Ticket, or nothing when full for this vehicleAlreadyInsideO(1)
leave(ticket_id)ReceiptUnknownTicket, PaymentDeclinedO(1) plus the card
free()Counts by sizeNeverO(1)
Pricing.price_cents(ticket, left_at)Whole cents, zero or moreNeverO(1)
Payments.charge(key, cents)NothingPaymentDeclined; may time outSeconds

Why it looks like this

  1. 1

    Two verbs

    No findSpot in public. If a gate can find without taking, somebody will build the race on top.

  2. 2

    Nothing for full

    A caller cannot forget an optional as easily as an exception. And it is not exceptional.

  3. 3

    No isFull()

    Full for whom? And the answer is old when it arrives. free() is for signs.

  4. 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?, or Full(size), AlreadyInside.
Limit
One more type if you want reasons.
Choose when
Here.