Systems that move step by step
Model a system that changes over time with a clear step rule.
Make time explicit
Elevators, games and schedulers change over time. Give them a step() or tick(now) method that applies one round of rules. Everything else is input that queues work for the next step.
Separate deciding from moving
Each elevator knows how to move one floor toward its stops. Which elevator takes a call is a separate decision, made by a dispatch strategy that looks at all of them. Change the strategy without touching movement.
step() {
for (const e of this.elevators) e.step(); // movement
}
request(floor: number, dir: Direction) {
const e = this.dispatch.choose(this.elevators, floor, dir); // decision
e.addStop(floor);
}
Key takeaways
- A step method makes time predictable.
- Entities move themselves.
- Decisions across entities live in a strategy.
Hands-on coding exercise
An elevator moves one floor per step() towards its next request, and opens (removes the request) when it arrives. Requests are served in the order they were made.
Moving in explicit steps lets a test put it in any situation and check exactly where it is.
class Elevator {
get floor(): number {
throw new Error("Not implemented");
}
request(floor: number): void {
throw new Error("Not implemented");
}
/** Moves one floor, or serves the request it is on */
step(): void {
throw new Error("Not implemented");
}
pending(): number[] {
throw new Error("Not implemented");
}
}
Run your solution against 4 automated tests in the interactive workspace:
Check your understanding
Answer these questions interactively to test what you learned and track progress on your skill map:
- Where should the rule "send the nearest idle elevator" live?
- Why drive the system with step() instead of real time?