Design a parking lot with object-oriented principles by treating it as a small model of a physical business: the lot owns floors, floors own spots, spots hold vehicles, and a parking service issues the tickets that tie a vehicle to a spot. The key condition is that vehicles and spots share a size hierarchy while the lot stays unaware of concrete vehicle types, so adding a new vehicle class doesn't force you to edit the lot's placement logic. This walkthrough builds that model in a language-neutral way, then shows Java-like sketches, the algorithms that make it correct, and the failure cases that separate a toy design from one you could actually deploy.
Start With the nouns, verbs, and invariants
Before writing a class, write three lists. Nouns from the problem statement become candidate classes: lot, floor, spot, vehicle, ticket, payment. Verbs become behaviors: enter, park, exit, pay, find a spot. Invariants become constraints your tests must defend: a car must never be assigned a motorcycle spot (or, if it can, the policy must say so); a ticket must reference exactly one active vehicle and one occupied spot; and the count of occupied spots on a floor must never exceed the floor's capacity.
The most common beginner mistake is skipping this step and letting the ParkingLot class accumulate every behavior. You get a 900-line god class that can't be tested without constructing an entire lot. The fix is a discipline: each class should have one reason to change, and each change should ripple to as few neighbors as possible. A useful sanity check is to ask, "If the price of motorcycle spots changes, or if we add electric-vehicle charging, how many files do I edit?" If the answer is "the lot and everything downstream," the boundaries are wrong.
| Noun | Responsibility | Key collaborators |
|---|---|---|
| ParkingLot | Aggregate root; owns floors, exposes entry/exit orchestration | Floor, ParkingService |
| Floor | Holds spots, reports free capacity by size | ParkingSpot |
| ParkingSpot | Identity, position, size, occupancy state | Vehicle |
| Vehicle | Abstract identity and required spot size | none (leaf) |
| Car, Motorcycle, Truck | Concrete size policies | Vehicle |
| Ticket | Links vehicle to spot; timestamps and status | Vehicle, ParkingSpot |
| ParkingService | Entry/exit use cases, allocation policy | ParkingLot, Ticket |
| SpotAllocator | Strategy for choosing a spot | Floor, ParkingSpot |
| FeeCalculator | Pricing policy based on duration and vehicle type | Ticket |
Model vehicles and spots with a shared size abstraction
The cleanest coupling between vehicles and spots is a single VehicleSize or SpotSize enum that both types reference. This keeps the dependency one-directional: a vehicle knows the smallest size it needs, and a spot knows the largest size it can accommodate. If you let Truck inherit from Spot or vice versa, you've imported physical nonsense into the type hierarchy.
A second, more flexible option is a fitsIn(SpotSize) method on Vehicle. A motorcycle returns true for every size; a car returns true for compact, regular, and large; a truck returns true only for large. This small polymorphism replaces a growing if/else ladder, and it's the first place where object orientation genuinely pays for itself.
The subtle policy decision is whether size compatibility is symmetric. A compact spot that holds a car is not the same as a car that can use a regular spot: a car can usually use a larger spot, but a truck cannot use a compact one. The fitsIn method encodes the asymmetry correctly because it's called on the vehicle with the spot's size as the argument. If your business instead enforces "compact spots are strictly compact vehicles only," that's a policy object, not a type hierarchy change — you swap the fitting predicate.
Build the lot as a three-level composition
A ParkingLot contains a List, each Floor contains a fixed Map<SpotSize, List> or a flat list of spots, and each ParkingSpot has a nullable Vehicle reference (or an Occupancy state object). Composition is the right relationship here: a floor doesn't exist after the lot is deleted, and a spot doesn't exist after its floor is removed. Aggregation would suggest the opposite lifecycles.
Keep the lot's public surface narrow. It should expose enter(Vehicle), exit(Ticket), and capacityBySize(), and nothing else. Everything else — pricing, allocation, ticket validation — belongs in the service or policy layer. This is also the point where a naive design leaks: many developers put a findSpot(Vehicle) method directly on ParkingLot, and by month three that method has accumulated charging-station checks, handicapped-spot rules, and overnight restrictions. A service layer with injected strategies absorbs that growth without changing the lot's interface.
A concrete test of this design: to unit-test the allocation policy, you construct a fake floor with ten spots and no lot at all. If your test requires constructing a ParkingLot object to test a single allocation rule, the composition is too deep for testability.
Separate allocation policy from the data structures
The allocation policy is where most real-world complexity lives, and it should be a separate object behind an interface. The simplest version is "first compatible free spot by size tier," but production lots often use "lowest floor first," "closest to elevator," or "prefer regular spots over large spots for cars to preserve large capacity for trucks."
The classic bug here is a car consuming a large spot and blocking a truck later. A good allocator ranks free spots by size fit tightness, preferring the smallest spot that fits the vehicle. That's a one-line ordering change that preserves premium capacity, and it's testable without touching the ticket system.
Keep the allocator stateless where possible; it should receive the floor and vehicle and return a spot or empty. Statelessness makes it easy to swap the strategy in tests and avoids the locking problems that come from a stateful "next spot index" shared across threads.
Design the ticket lifecycle and its state transitions
A Ticket is the aggregate that guards a parking session. It should hold a unique ID, the vehicle, the assigned spot, an entry timestamp, an exit timestamp (nullable), and a status enum: ACTIVE, PAID, EXITED, VOID. Every method that mutates the ticket should assert the current status; calling pay() on a ticket that's already EXITED should throw, not silently succeed.
Entry enter(vehicle) sequence:
1: Validate the vehicle isn't already active in the lot (check the active-ticket registry by license plate). 2: Ask the lot for a compatible free spot. 3: If none, return a typed failure (lot full for that size) rather than null. 4: Reserve the spot, create a ticket, and register the plate in the active set.
Exit exit(ticketId) sequence:
1: Look up the ticket by ID; reject unknown or non-active IDs. 2: Compute fees from entry/exit timestamps and the vehicle class. 3: Require payment (or a payment authorization) before release. 4: Mark the spot free, close the ticket, remove the plate from the active set.
A success check after entry: the ticket is ACTIVE, the spot's occupancy equals the ticket's vehicle, and the lot's free count decreased by exactly one. After exit: the spot is free, the free count returned to its prior value, and the plate is absent from the active set. These three assertions catch nearly every inconsistency the classic design produces.
Make the fee calculator a strategy, not a switch statement
Pricing rules change more often than any other part of the system: weekend rates, overnight flat fees, lost-ticket charges, discounts, and validation by merchants. If pricing lives in an if tree inside ParkingService, every pricing change requires retesting the core flow. A FeeCalculator interface with a Duration and Vehicle input, returning a Money value, keeps that volatility contained.
A worked example: suppose the lot charges 25 cents per 20 minutes for cars on weekdays, 50 cents per 20 minutes on weekends, and a 10-dollar lost-ticket fee with no time charge. A car enters Tuesday at 09:10 and exits at 11:05 — 115 minutes, which rounds up to 6 billing units of 20 minutes, so 150 cents. On Saturday, the same duration costs 3 dollars. The rounding rule ("any partial 20-minute block counts as a full block") must be explicit; it's the difference between a $1.50 and a $1.75 ticket, and ambiguous rounding is the most common source of customer disputes. Use exact durations internally (nano or seconds) and convert to billing units once, in a single method.
Also model money as an integer of the smallest currency unit, or a decimal type, never as a float. Floating-point accumulation of 25-cent increments produces cent-level drift that shows up in reconciliation.
Reconcile the parking-lot interview answer with a deployable system
The classic object-oriented-interview version of this problem is small and elegant: Vehicle, ParkingSpot, ParkingLot, Ticket. It works for teaching the shape of the design, and its size hierarchy insight is genuinely correct. But the deployable version needs five things the interview version usually omits, and recognizing the gap is more valuable than the idealized diagram.
First, concurrency: two vehicles entering at the same instant must not both be assigned the same spot. A billography reserved count or a per-floor lock around reservation fixes this. Second, persistence: the ticket ID must survive a process restart, so the lot can't be the only source of truth. Third, pricing volatility, as covered above. Fourth, reporting: occupancy history tells you where capacity should be added, and that's a separate read model. Fifth, auditability: every ticket mutation should have an operator or automation identity attached.
A fair comparison of the two versions across shared criteria:
| Criterion | Interview design | Production design |
|---|---|---|
| Core classes | 4–5 | 10+ with policy interfaces |
| Allocation | hardcoded search | injected allocator |
| Pricing | method on lot | strategy + versioned rules |
| Concurrency | ignored | per-spot reservation |
| Persistence | in-memory | repository + ticket store |
| Testability | whole-lot tests | per-policy unit tests |
Neither column is "wrong." The interview design is the right size for a whiteboard; the production design is the right size for a system that must survive a Monday morning rush and an auditor.
Expose behavior through interfaces and hide the data
The most valuable principle in this design isn't inheritance; it's encapsulation. Callers should never reach into a spot and set its vehicle field directly. Instead, spot.assign(vehicle) and spot.release() are the only mutators, and they return whether the operation was legal. That makes illegal states hard to construct: you can't have a spot with two vehicles, or a released vehicle still pointing at a spot.
Try the "tell, don't ask" test: if a client says if (spot.isEmpty()) spot.setVehicle(v); it has read the state, then written it, and bet that nothing changed between those two lines. That's the concurrency bug in miniature. Rewriting it as if (!spot.assign(v)) { throw ... } moves both the check and the mutation inside the object where they can be atomic with respect to other threads.
Apply the same discipline to the ticket. Rather than letting the client compute fees, ticket.close(exitTime, calculator) does both the transition and the calculation together, in one place, under one lock. This isn't just style — it reduces the number of states the system can be in.
Handle the edge cases that decide whether the design survives contact with reality
Several edge cases separate a working model from a robust one, and a good design facility is to write each as a test before writing the code.
Full lot with incompatible capacity. A lot with free motorcycle spots but no car spots is not "full" in a general sense; the entry method should report a size-specific failure so the driver gets a useful message and the dashboard shows a useful picture. Lost tickets. The design needs a "vehicle identified by plate, ticket not found" path that charges the lost-ticket fee and still releases the spot. Without it, a lost ticket permanently leaks capacity. Overstayed vehicles. If the lot has a maximum stay, the ticket must have a deadline, and enforcement — towing or fines — should be a separate service that reads tickets, not a method on the ticket itself. Reserved or handicapped spots. These should be modeled as spot attributes with an assignment predicate, not subclasses, unless their behavior genuinely diverges. A ReservedSpot class with no overridden behavior is just a boolean with extra ceremony. Random access vs. sequential entry. If the lot has multiple gates, the "first free spot" policy should include gate affinity, or cars will snake through the entire structure to find the spot a central allocator chose.
The stop condition for in-house work here is when the design grows a second vehicle type, a second pricing scheme, and a payment processor in the same sprint. At that point the policy layer needs its own boundaries, tests, and probably a real database transaction boundary; beyond that, a commercial parking-management system may beat a homegrown one on auditability and payment compliance. That's a business decision, not a code refactor.
Worked mini-example: walking two sessions end to end
To see all the pieces cooperate, trace two entries and exits through the design above. The floor has two regular spots and one motorcycle spot, all free at 08:00.
08:00: a car enters. The active registry has no entry for its plate; allocator.allocate(floor, car) returns the first regular spot (tight fit prefers compact, none available, so regular); the spot's assign(car) succeeds; a ticket T1 is created with entry time 08:00 and status ACTIVE; the active registry now has one entry. Free counts: regular 1, motorcycle 1.
08:10: a motorcycle enters. Its fitsIn calls return true for the motorcycle spot, and tight-fit ordering assigns it there. Ticket T2 is active. Free counts: regular 1, motorcycle 0.
11:05: T1 exits. Fee calculator multiplies 185 minutes by the per-20-minute rate with rounding up; ticket status becomes PAID then EXITED; spot.release() frees the regular spot; the active registry removes the car's plate. Free counts: regular 2? No — the motorcycle is still parked, so regular 1 is freed, not 2. Let's re-check: before exit, regular free = 1 (one car parked, one regular free). After exit, regular free = 2. Motorcycle free = 0. Good. The check that the free count change is exactly +1 in the correct category, and no other category, catches the bug where a release mistakenly frees a spot of the wrong size.
11:30: T2 exits. Its motorcycle spot is released. Free counts back to regular 2, motorcycle 1. The invariants — one active ticket per vehicle, occupancy matching the registry — hold throughout, and each step's assertions are the three-line checks that keep the model honest.
FAQ
Is a ParkingSpot subclass for each size a good idea? Usually no. If a CompactSpot and LargeSpot differ only in a size field, a subclass adds a class without adding behavior, and a size enum plus a fitting predicate preserves flexibility. Subclass only when the behavior genuinely differs — for example, a ChargingSpot with an attachCharger protocol.
Should the ticket or the service own the fee calculation? The service orchestrates, and a FeeCalculator strategy owns the formula. Putting pricing on the ticket couples a long-lived entity to changing pricing rules; putting it only in the service couples the service to every rule. Splitting them keeps both stable.
What if the lot has a valet, so the spot assignment is made by a person? Then the allocation becomes an assignment command with an operator identity, and the design adds an Attendant or Operator role that records the assignment. The rest of the model — ticket, fee, release — is unchanged, which is the point of separating allocation from the aggregate.
How many floors and spots should the design support? The review date for this walkthrough is November 13, 2026, but the model is size-agnostic: a single-floor lot and a fifteen-floor structure use the same types because the lot is a list of floors of uniform shape. The design's complexity should scale with the diversity of vehicles and policies, not with the raw count of spots.