Part 5 of 6 · 3 min read
Edge cases and changes
Capacity, priorities and bad calls.
Step 5: edge cases, tests and change requests
Edge cases:
| Case | Behaviour |
|---|---|
| Press the same floor twice | The set holds it once |
| Press the current floor while moving | The car is past it, so the stop is served on the return sweep |
| Two calls at once for the same car | addStop is called twice, and both stops are kept |
| All cars busy | The lowest cost still wins, and the call waits in the car's stop set |
| A request while the door is open | The stop is added and the car moves on the next tick |
| Many threads press buttons | Make Elevator methods synchronized, or run all calls on one control thread |
One weakness should be said aloud. A stop for floor 3 added while the car is at floor 5 going up is served only after the car has turned. That is fair to the car's current passengers and slow for the new caller. This trade-off is the heart of every scheduling rule.
Tests to write first: each row of the run table; a call behind a moving car; two cars with equal cost (the first wins, so say so); the bad floor; and a long run of random presses that ends with every car idle and no stops left.
Change requests and the part that changes:
- "Capacity limit." Track the load and skip hall calls when full. This touches
costandstep. - "Express cars that skip floors." A set of served floors per car.
- "Peak hours: send idle cars to the lobby." A new rule in
Building.tick, or an idle-handling strategy. - "Priority for a VIP or a fire fighter." A priority flag on a stop and a new dispatcher.
- "A different dispatch rule." A new
Dispatcherclass. Nothing else changes. - "Show direction lights and a display." Observers on the car (Level 4, module 2).
- "Door-open time." The door state stays open for more than one tick, using a counter.
Common mistake
Serving stops in the order they were pressed. The car then zigzags between floors. Keep stops sorted and sweep in one direction before turning.
Interview angle
Answer in your head first, then open it.
How does one car decide where to go?
A sorted set of stops, a direction, and the sweep rule: keep going while a stop lies ahead, then turn.
How do you choose a car for a hall call?
A cost for each car, the lowest wins, in a replaceable dispatcher.
What is the state machine?
Direction up, down or idle, and door open or closed, with step as the only transition.
How would you test it?
Drive time with tick, and check floors and doors after each tick.
Check yourself:
1. Why is a call behind a moving car costly?
2. Which change request needs only a new Dispatcher?
3. How can threads be kept from corrupting the stop set?
Words you will meet
| Word | Meaning |
|---|---|
| Hall call | A press outside the car asking for a ride up or down |
| Stop | A floor the car has been asked to visit |
| Dispatcher | The object that assigns a call to a car |
| Tick | One unit of simulated time |
| Idle | Not moving and with no stops |