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
Problem
What is asked, and how to take it apart
The point: the problem is two verbs, enter and leave, and one rule: a space is never given to two vehicles.
The prompt
What they say, and what they mean
The first minute
Interviewer
Design a parking lot.
You
I will design the software that decides who gets which space and what they pay. Before I draw, may I ask a few questions?
Interviewer
Please.
You
Let me start with the ones that change the design:
- How many levels and spaces, and is the layout fixed while it runs?
- Which vehicles, and may a small one use a larger space?
- How is the price made, and how often does that rule change?
- How many entrances? More than one means two threads can want one space.
Interviewer
Several levels, three sizes. Motorcycles, cars, buses. Per hour for now, marketing has ideas. Four gates in, three out.
You
Then concurrency is in scope, pricing goes behind an interface, and I will treat payment as a machine somebody else owns. Booking, electric charging and lost tickets I will leave as extensions and show where they fit.
The picture
What we are modelling
A level of ten spaces, as an example layout
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
|---|---|---|---|---|---|---|---|---|---|
| S | S | M | M | M | M | M | M | L | L |
From a vague problem to code in five steps
- 1
Clarify
Levels, sizes, vehicles, prices, gates. Write the answers down where both can see them.
- 2
List the nouns
Vehicle, space, level, lot, ticket, gate, fee, payment, sign. Then strike out those that are not classes.
- 3
Relate them
Is a, has a, uses a. Most answers here are has a and uses a.
- 4
Draw
Boxes with state and methods. Two public methods on the lot, the rest stays inside.
- 5
Write the verbs
enterandleave, and the parts they need. Then trace them with real values.
A checklist
C.I.M.P.L.: five places to look
When a blank board stares back, walk through five words. Each one produces a few candidates, and most problems of this kind have all five.
| Letter | Question | Here | In code |
|---|---|---|---|
| Container | What holds the resources? | The lot, its levels, its free spaces | ParkingLot, SpotPool |
| Item | What is stored or processed? | Vehicle, space, ticket | Records |
| Manager | Who runs the operation? | The gate asks, the lot does | enter, leave |
| Policy | What varies? | Price, choice of space, who fits where | Pricing, the claim rule |
| Lifecycle | Which states are there? | Space: free, taken. Ticket: active, paid, left | Queue membership, map membership |
In scope today
- Enter and leave
- Three sizes with fallback
- Hourly price, replaceable
- Several gates at once
- Free counts for a sign
Out of scope, said aloud
- Booking ahead
- Monthly passes
- Number plate cameras
- Finding your car again
- Several car parks in one system