LOAD-BEARINGfree
Low-level design dojoTier 13 · unit 20 of 31

Parking lot

Multi-level lot. Spot sizes for bike, car and truck. Vehicles get a ticket on entry and pay on exit. Pricing rules change often, and management wants to experiment with allocation policy.

Assign each responsibility to the class that should own it.

Compute fee from duration and vehicle type
PricingStrategy
Record entry time, spot ID and vehicle
Ticket
Choose which free spot a vehicle gets
SpotAllocator
Track which spots exist and their occupancy
ParkingLot
Decide weekend vs weekday rates
PricingStrategy
Prefer the level nearest the entrance
SpotAllocator
Why

A Ticket is a record of fact — it stores, it does not calculate. Pricing and allocation are the two rules that change most often, so each gets its own strategy. ParkingLot owns inventory and coordinates; it must not accumulate pricing logic, or every rate change edits the same file as every allocation change.

Management wants to A/B test "nearest spot" against "least congested level". Which structure fits?

  • A boolean flag inside ParkingLot.park()
  • A SpotAllocator interface with two implementations, injected at construction
  • A subclass of ParkingLot for each policy
  • A static utility class with both methods
Why

Strategy. The policy varies independently of everything else and will grow, so it becomes an injected collaborator. Subclassing ParkingLot couples the policy to the lot itself and breaks the moment you want a second axis of variation.

Two entry gates assign the last free spot at the same moment. The system runs on three servers. What actually fixes it?

  • synchronized on the allocate method
  • A conditional UPDATE that only succeeds if the spot is still free
  • An ArrayList of free spots
  • Making Spot immutable
Why

Three servers means three separate in-process locks, which protect nothing. The check and the claim must be one atomic operation at the shared source of truth: UPDATE spots SET ticket_id=? WHERE id=? AND ticket_id IS NULL, then verify rows-affected is 1.

Where should the rule "a truck cannot park in a compact spot" live?

  • In the UI validation only
  • In Spot.canFit(vehicle), enforced on assignment
  • In a comment on the Vehicle class
  • In the PricingStrategy
Why

Tell, do not ask. The invariant belongs with the object that owns the state, so there is exactly one place it can be violated. Validation in the UI is a convenience, never a guarantee.