Notes
Requirements
Fix the scope. One crossroads with a north-south road and an east-west road. Each approach has a red, yellow and green light. The two roads take turns, and each road can have its own green time. A walk button stops all cars so people can cross. An emergency vehicle gets green on its road as soon as it is safe. Above everything: two crossing roads never show green together. Turn arrows and cameras are out of scope.
Ask for the numbers and the failure rules. Green is thirty seconds for north-south and twenty for east-west. Yellow is four seconds and an all-red gap is two. The walk phase is twelve seconds. A green must last at least eight seconds, so drivers are not surprised. Two ambulances at once? The first one wins. And if the logic ever fails, every light flashes red, which drivers treat as a four-way stop.
- one crossroads: north-south and
- east-west roads
- lights: red, yellow, green
- roads take turns, timed per road
- walk button: all cars stop,
- people cross
- emergency vehicle: its road
- gets green as soon as safe
- never two crossing greens
- out of scope: turn arrows, cameras
- green times?
- north-south 30s, east-west 20s
- yellow? 4s, all red? 2s
- walk phase? 12s, all roads
- shortest green? 8s minimum
- two ambulances at once?
- first one wins, then the next
- what if the logic fails?
- flash red: a four-way stop
Entities
Underline the nouns: intersection, road, signal, light, phase, timer, button. The intersection has four signals, one per approach. The controller is the brain: it holds the current phase, when that phase ends, and any waiting requests. A phase is one step of the cycle, like north-south green. Timing is a small record of durations, and the clock is injected so tests control time.
Class diagram
In code: an axis is either north-south or east-west, and knows the other one. A light is red, yellow or green. Each of the four directions belongs to an axis, because north and south always show the same colour. Timing is one immutable record with the green time per road, yellow, all red, walk and minimum green, so a new timing plan for rush hour is just a different record.
enum Axis { NORTH_SOUTH, EAST_WEST;
Axis other() }
enum Light { RED, YELLOW, GREEN }
enum Direction { NORTH, SOUTH,
EAST, WEST; final Axis axis; }
record Timing(int greenNorthSouth,
int greenEastWest, int yellow,
int allRed, int walk, int minGreen) The naive way
The first version people write is one loop with a colour variable, a chain of if statements, and sleep calls. Every new rule, a walk button, an ambulance, a night mode, adds a check inside every branch, and they slowly disagree with each other. Worse, testing a thirty second green means waiting thirty real seconds. We fix both problems: the State pattern for the rules, and a simulated clock for time.
while (true) {
if (color == GREEN) {
if (walkPressed) ...
if (siren) ...
sleep(30_000); color = YELLOW;
} else if (color == YELLOW) {
if (siren) ...
} ...
}
every new rule: edit every branch State pattern
Each phase becomes a small class implementing one interface: the State pattern. A phase answers three questions: what light does each road see, how long do I last, and which phase comes next. It also decides how to react to events, like a walk button or a siren, with safe defaults that do nothing. The controller never asks which phase it is in. It just delegates to the current one.
Light lightFor(Axis a);
long duration(Controller c);
Phase next(Controller c);
default void onWalkRequest(c) {}
default void onEmergency(c, axis) {}
default void onEmergencyCleared(c) {}
Green, Yellow, AllRed, Walk,
EmergencyGreen, FlashingRed The normal cycle
Here is the normal cycle. North-south green for thirty seconds, then yellow for four, then all red for two, then east-west green for twenty, yellow, all red, and back to the start: sixty two seconds in total. Notice the shape: green always goes to yellow, yellow always goes to all red, and only the all-red phase decides what runs next. That one decision point is where walk and emergency requests plug in.
- NS GREEN 30s
- NS YELLOW 4s
- ALL RED 2s
- EW GREEN 20s
- EW YELLOW 4s
- ALL RED 2s
- cycle = 62 seconds
- Yellow.next() is always AllRed
- AllRed.next() picks what is next
Safety by design
Safety comes from the structure, not from careful if statements. Every phase lights at most one axis. A green can only be followed by its own yellow, and every change of road passes through all red, so the junction clears before the other road moves. Even the emergency path follows this route. Events can make a phase end sooner, but they can never jump the order.
- Green(a): only a is green
- Yellow(a): only a is yellow
- AllRed: nobody moves
- Walk: nobody moves
- Emergency(a): only a is green
- Green.next() is Yellow, always
- any change of road passes
- through AllRed
Conflict monitor
Real signal cabinets also have an independent conflict monitor, and so does our design. Every phase change passes through it first. It rejects two axes that are not red, a green that jumps straight to red, and a walk signal while cars can move. If any rule is broken, the controller enters flashing red instead. The demo injects a buggy phase that turns both roads green, and the monitor catches it.
both axes not RED? -> "conflicting greens" GREEN straight to RED? -> "green to red, no yellow" walk while cars can move? -> "walk with moving cars" violation: enter FlashingRed instead of the bad phase
Timing without sleep
Now time. The controller does not sleep. It stores when the current phase ends. Each tick compares the clock with that deadline, and while the deadline has passed it enters the next phase, starting it exactly at the old deadline so no time drifts. On a real device a timer calls tick ten times a second. In tests a simulated clock moves forward one second at a time, so two hundred seconds run instantly.
while (clock.now() >= phaseEnd) enter(phase.next(this), phaseEnd); enter(next, at): phaseStart = at; phaseEnd = at + next.duration(this); real device: tick every 100 ms test: clock.advance(1) in a loop
Walk button
The walk button shows why states are useful. Pressing it sets a waiting flag and tells the current phase. A green phase reacts by ending early, but never before its minimum green. Yellow and all red do nothing, because they end soon anyway. Then the all-red phase sees the flag, clears it, and returns a walk phase instead of the next green. In the demo, a press at ten seconds gives walk at sixteen seconds.
pressWalk(): walkWaiting = true; phase.onWalkRequest(this); Green: end at start + minGreen Yellow, AllRed: do nothing AllRed.next(): if walkWaiting clear it, return new Walk(..) press at 10s: yellow 10s, all red 14s, walk 16s
Emergency override
Emergency override follows the same idea. If the ambulance's road is already green, the green phase simply swaps itself for an emergency green that is held, so the light never changes in front of it. If the other road is green, that green ends after its minimum time, and the normal yellow and all red follow. All red always gives the emergency road priority. The emergency green lasts until someone clears it.
- Green on the same road:
- switch to EmergencyGreen now
- Green on the other road:
- end after minimum green,
- then yellow, then all red
- Yellow, Walk: finish safely
- AllRed.next(): emergency first
- EmergencyGreen: held until
- emergencyCleared()
Flow: an ambulance
Follow the demo. At seventy seconds north-south has been green for fourteen seconds, more than the minimum, when an ambulance approaches on east-west. North-south goes yellow at once, all red at seventy four, and east-west gets an emergency green at seventy six: six seconds, the fastest safe time. When it passes at one hundred, east-west goes yellow and normal cycling resumes. A second ambulance on an already green road waits zero seconds.
Observer: signals
The lamps themselves are observers. Each signal subscribes to the controller and, on every phase change, asks the new phase which light its axis should show and whether walk is lit. The controller does not know how many signals exist. A countdown display for pedestrians, a log for the traffic department, or a test that records every phase all subscribe the same way.
Concurrency
In a real cabinet, button presses, siren detectors and the timer arrive on different threads. If a walk press and a tick change the phase at the same moment, the order could break. So every public method of the controller is synchronized, and all phase changes go through one private method under that lock. Pressing walk twice is harmless. An alternative is one event-loop thread that reads events from a queue.
- tick, pressWalk, emergency and
- emergencyCleared: synchronized
- phase changes happen in one
- place, under one lock
- pressing walk twice: no-op
- second siren: ignored until clear
- or: one event-loop thread and
- a queue of events
Extensibility
Extensions fit the same shape. Left turn arrows are more phases plus more conflict rules in the monitor. Road sensors can extend a green while cars keep arriving. Night mode is a flashing yellow phase. A rush hour plan is just a different timing record. A green wave along a main road offsets the cycle start of neighbouring junctions, and a city-wide coordinator can push new timing plans to each controller.
- turn arrows: more phases
- and more conflict rules
- car sensors: extend green
- while cars keep coming
- night mode: flashing yellow
- rush hour: a new Timing record
- green wave: offset the start
- of nearby junctions
- many junctions: a central
- coordinator sends Timing
Testing
The full code is below the player. A loop advances the simulated clock one second at a time for two hundred seconds, presses the walk button, and sends two ambulances, one on a red road and one on a green road. After every second it checks the lamps directly: never two crossing roads moving, never walk with moving cars. Finally it injects a buggy phase and proves the monitor turns it into flashing red.
t= 10s walk button pressed t= 10s NORTH_SOUTH YELLOW t= 16s WALK t= 70s ambulance on EAST_WEST t= 76s EAST_WEST EMERGENCY GREEN t=150s ambulance on EAST_WEST t=150s EAST_WEST EMERGENCY GREEN Walk waited 6s, ambulance 6s then 0s 22 changes checked, 0 conflicts Fault test: FLASHING RED
Follow-ups
Expect follow-ups. Why the State pattern instead of a switch? Each phase keeps its own rules, and new phases do not touch old ones. Why an all-red gap? It lets cars that entered on yellow clear the junction. How do you test timing? Inject a clock. Ambulances from both roads? Queue them and serve one after another. And if the controller itself crashes, the hardware falls back to flashing red.
- why State, not a switch?
- why an all-red gap?
- how do you test timing?
- inject a clock, no sleeps
- ambulances from both roads?
- queue them, serve in order
- controller crashes?
- hardware falls back to
- flashing red
Say it like this
Here is the short version to say out loud. Each phase is a state that knows its lights, its duration, the phase after it, and how to react to walk and siren events. Green always goes to yellow, and every change of road passes through all red. An independent conflict monitor checks each change and falls back to flashing red. Time comes from an injected clock, so tests run instantly.
- "Each phase is a State that
- knows its lights, duration,
- next phase and how it reacts
- to walk and siren events.
- Green always goes to yellow,
- every road change passes all
- red, and a conflict monitor
- checks each change. Time comes
- from an injected clock."