Object-Oriented Design Interview

Course Content

Object-Oriented Design Interview

14 sections · 29 lessons

Elevator System: requirements and separating the dispatcher from the car


Every earlier problem in this course has a right answer. The elevator does not: which car should answer a call is a policy decision made against a future nobody can see. This lesson covers the prompt, the questions and requirements that make that policy decidable, and the one modelling choice that decides whether the rest of the round goes well.

Five questions before any box is drawnDesign anelevator bankHow many cars, floors?Hall or destination?Optimise wait or ride?Is capacity modelled?Ticks, or real time?
Whether the panel is in the hall or in the car decides what a request object even contains.

Why this problem is hard

Every other problem in this course has a right answer. This one does not. The scheduling policy — which car should answer a call on floor 7 going down — has no optimal solution, because you are optimising against a future you cannot see. Real elevator dispatching is an active engineering field, and the interviewer knows it.

That changes what is being scored. Nobody expects the perfect algorithm. They expect you to notice there is a policy decision, separate it from the mechanism, present two or three options with their trade-offs, and recommend one with a reason. A candidate who confidently asserts one scheduling rule as correct scores below a candidate who says "there are three reasonable policies here, and which is right depends on what the building is optimising for".

The five questions that change the model

1. "How many elevators and how many floors?" One elevator removes the dispatch problem entirely and makes this a much easier round. Assume three to six cars, ten to twenty floors — enough that dispatch matters.

2. "Are there express floors, restricted floors, or basements?" Restricted floors (needing a keycard) and express cars that only serve floors 10–20 are constraints on which car can serve which request. Assume none for the core, and treat them as an extension.

3. "What are we optimising — average wait, worst-case wait, or energy?" This is the best question you can ask on this problem, and most candidates never ask it. The three goals give three different algorithms, and asking makes the policy discussion in Scheduling as a Strategy concrete rather than abstract. Assume average wait, with no request starved.

4. "Is there a weight limit or a capacity limit?" Capacity means a full car must skip waiting passengers, which affects both the state machine and dispatch. Mention it; keep it as an extension.

5. "Destination dispatch, or traditional up/down buttons?" In a destination-dispatch building you enter your floor in the lobby and are told which car to take. It is a genuinely different problem with better solutions. Assume traditional, and raise destination dispatch in the extensions — knowing it exists is a strong signal.

Assumptions this lesson makes

  • Four cars, fifteen floors, no basements or express floors.
  • Traditional hall buttons (up and down) on each floor, plus floor buttons inside each car.
  • Optimising average wait time, with a hard rule that no request may be starved.
  • Doors take a fixed time to open, stay open, and close; a door sensor can re-open them.
  • One controller process; cars report their position through an interface.

Requirements

Functional requirements

Text
1. Accept a hall request: floor + direction (someone waiting outside)2. Accept a car request: destination floor (someone already inside)3. Assign each hall request to exactly one car4. Move a car toward its next stop, one floor at a time5. Open and close doors at a stop, with a hold time6. Report each car's floor and direction to displays

Requirements 1 and 2 are deliberately separate, and keeping them separate is a scored modelling decision — finding the objects, below, explains why.

Two request types, deliberately kept apartHall request• Made from a floor, with a direction• Belongs to the whole bank• Any car may be assigned to itCar request• Made inside one car, names a floor• Belongs to that car alone• Never reassigned to another car
Merging the two request types is the modelling mistake that makes dispatch impossible to write.

Non-functional requirements

N1. No request may be starved. A car that keeps getting closer calls must eventually serve the person on floor 2 who has been waiting four minutes. Any policy needs an ageing rule, and saying this unprompted is a strong signal.

N2. A car must not oscillate. Without a rule, a car travelling up that receives a request below can reverse, then reverse again, and passengers inside travel in the wrong direction. The fix is direction commitment — The car state machine.

N3. The scheduling policy must be replaceable without touching the cars. The building manager wants to try a different rule; that must not be a rewrite. This forces the Strategy in Scheduling as a Strategy.

What is cut

Text
CUT (named, not forgotten)- Fire service mode and emergency override (extension)- Maintenance/out-of-service mode (extension)- Weight sensors and capacity (extension)- The physical motor control loop and safety interlocks- Building access control and keycards

Say the last one out loud: "Safety interlocks are real and are handled below this layer in hardware — I'm designing the dispatch and lifecycle logic, not the safety system." That sentence prevents a long tangent and shows you know where the boundary is.

The number that makes the problem concrete

A fifteen-floor office building, four cars, morning rush. Rough figures worth stating:

  • A car takes roughly 2 seconds per floor travelled and about 8–10 seconds per stop (decelerate, open, hold, close, accelerate).
  • So a car serving 6 stops across 15 floors takes roughly 30 + 55 ≈ 85 seconds for one sweep.
  • With 4 cars, the theoretical best average wait during a heavy rush is tens of seconds, not seconds.

These are order-of-magnitude figures for reasoning, not measurements. Their value is that they make the policy comparison in Scheduling as a Strategy real: stops cost about four times as much as floors, which means a good policy avoids extra stops more than it avoids extra distance.

Finding the objects

The candidate nouns

Building, elevator, car, floor, request, button, door, display, controller, dispatcher, direction, passenger, panel.

The decisive modelling choice

There is one decision in this problem that determines whether the rest of it goes well: separate the thing that decides from the thing that moves.

Put dispatching inside ElevatorCar and every car needs to know about every other car, so they can decide which of them should take a call. That is n cars each holding n references and a distributed agreement problem you have invented for no reason.

Keep them separate:

Text
ElevatorController — receives every request and decides which car serves it.ElevatorCar        — moves itself to its next stop and manages its own doors.DispatchStrategy   — given the cars and a hall request, names the car that should serve it.

A car knows only about itself. The controller knows about all cars but nothing about how to choose — that is delegated to the strategy. Three responsibilities, cleanly separated, and the policy from requirement N3 becomes replaceable because it is already its own object.

Say this out loud when you draw it: "I'm keeping dispatch out of the car. A car should know how to move itself and nothing about the others — that way the scheduling policy is one object I can swap, and the car logic never changes when the policy does."

Two kinds of request, not one

The second modelling decision. A hall request and a car request are different:

Hall requestCar request
Made bySomeone waiting, outsideSomeone riding, inside
CarriesFloor and directionFloor only
Assigned toOne car, chosen by the dispatcherThe car they are already in
Can be reassignedYes, before serviceNo
If unservedA person is left standingA person is trapped

Modelling both as one Request class with a nullable direction loses all of that. Model them as two:

Java
public abstract class Request {    private final int floor;    private final Instant createdAt;      // needed for the ageing rule in N1}public class HallRequest extends Request {    private final Direction direction;    // UP or DOWN    private String assignedCarId;         // null until dispatched}public class CarRequest extends Request {    private final String carId;           // never reassigned}

This is a legitimate two-variant hierarchy by the test in Inheritance, and its limits.

The rest of the model

ClassIts one-sentence job
BuildingHolds the floors and the controller; thin
ElevatorControllerReceives requests and assigns them to cars
DispatchStrategyChooses which car should serve a hall request
ElevatorCarMoves to its next stop and manages its own state
StopListHolds one car's pending stops in service order
DoorOpens, holds, closes, and reports obstruction
Request (+ two subtypes)One person's need to travel
DisplayShows a car's floor and direction; thin, read-only
ElevatorSystem- cars: List- dispatcher: Dispatcher+ requestFloor(from, dir)+ step()«interface»Dispatcher+ assign(Request, List) CarNearestCarDispatcher+ assign(...) CarElevatorCar- id: int- currentFloor: int- direction: Direction- state: CarState- door: Door+ addStop(int)+ step()+ nextStop() int?Request- floor: int- direction: Direction- source: RequestSourceDoor- state: DoorState- obstructed: boolean+ open()+ close()«abstract»Panel+ press(button)CarPanelFloorPanel11..*asks11pending stops0..*createsnotationcomposition — owns; dies with itaggregation — has, but can outliveimplements an interfaceDispatcher is an interface because thescheduling policy is the part the interviewerwill change on you.
Two panel types create the same Request, which is what lets one dispatcher serve both hall calls and car calls.