Skip to content

State Entry, Exit and Do Behavior

A state in a state machine can own behavior. (See State Machine Diagram for the basics.) Three kinds exist: entry, do and exit.

Entry and exit belong to the state. They do not belong to any transition. So they run whenever the state is entered or left, no matter which path was taken.

The do activity runs in between. It starts only after the state is entered and the entry behavior has finished. It is an ongoing activity that lasts while the state is active.

Leaving a state follows a fixed order. The do activity is aborted first. Then the exit behavior runs. This is also how an event interrupts a do activity. The event triggers a transition out of the state, and leaving the state aborts the activity.

Finishing normally. When the do activity finishes, an outgoing completion transition can move the machine to the next state. A completion transition has no event of its own. It fires as soon as its source state is active, unless a guard (a condition on the transition) forbids it.

Internal transitions. An internal transition handles an event inside the state. It acts like a self-transition without entry or exit actions. A self-transition leaves and re-enters the state, so it runs exit and entry actions. An internal transition never does. The state is not left, so the do activity is not aborted.

Why it matters for modeling. Entry and exit actions are tied to states. For that reason, statecharts behave like Moore machines. Event-dependent actions placed on transitions are Mealy-like.

A state named “Heating” in a kettle model:

  • entry: switch the heating element on
  • do: monitor the water temperature
  • exit: switch the heating element off

The kettle may leave “Heating” because the water is hot or because someone lifts it off the base. Either way, the monitoring stops first and then the element is switched off. If the kettle only reports a temperature reading, an internal transition can handle that event. The state is not left, so monitoring continues.

Putting behavior on the state avoids repeating it on every incoming or outgoing transition. The cost is that it runs on every entry and exit, including self-transitions. If you want to react to an event without that, use an internal transition instead.

A state with entry, do and exit behavior.

Diagram source
@startuml
[*] --> Heating
state Heating {
}
Heating : entry / element on
Heating : do / monitor temperature
Heating : exit / element off
Heating --> Idle : lifted off base
Heating --> Done
Done --> [*]
@enduml
  • Entry and exit behaviors are attached to states, not duplicated on each transition.
  • Events that must not restart a state or abort its do activity are modeled as internal transitions, not self-transitions.
  • A state with a do activity has an outgoing completion transition, or an event transition that interrupts it.