What are entry/exit actions and why do they matter for safety-critical code?
Entry and exit actions are side effects attached to a state, not to a specific transition. The entry action runs every time the system enters the state, regardless of which transition led there. The exit action runs every time the system leaves the state, regardless of which transition leads out.
For safety, this matters because entry/exit actions encode invariants — properties that must hold structurally, not by convention.
Example: a motor controller with a MOTOR_RUNNING state. Safety requires that whenever the motor is running, the brake is released, and whenever it's not running, the brake is engaged. Two ways to encode this:
Wrong: put release_brake() on every transition that enters MOTOR_RUNNING (from IDLE, from RECOVERY, from MAINTENANCE...) and engage_brake() on every transition that leaves it. Six months later, someone adds a EMERGENCY → MOTOR_RUNNING transition and forgets the release. Silent safety violation.
Right: put release_brake() in the entry action of MOTOR_RUNNING and engage_brake() in the exit action. Now no matter how the state is entered or left — by user command, by sensor trigger, by recovery from fault, by future code added years later — the brake is released on entry and engaged on exit. The invariant is structural; the framework guarantees it.
For safety certification (ISO 26262, IEC 62304, DO-178C), this kind of structural guarantee is much easier to argue. You can point to the state diagram and say "the brake is engaged whenever we're not in MOTOR_RUNNING because of the exit action — and we never bypass the entry/exit framework." A reviewer can verify this by checking that all transitions go through the proper dispatch path, not by reading every if.
The same argument applies to:
- Watchdog management:
WORKINGstate's entry starts the watchdog; exit stops it. Any state where the watchdog isn't being kicked is an exit-from-WORKING. - Resource locks:
EXCLUSIVE_ACCESSstate's entry acquires the lock; exit releases it. No code path can leave with the lock held. - LED indicators: the visual state matches the FSM state by construction, not by convention.
- Logging: entry to
FAULTtriggers diagnostic capture; exit triggers diagnostic flush.
The interview answer is: entry/exit actions encode invariants structurally; per-transition actions encode opt-in side effects. For anything safety-related, prefer the structural guarantee — the bug surface is much smaller.
Source: State Machines Q&A
