[erlang-questions] gen_fsm - calling state function clauses directly (question from Learn You Some Erlang chapter 20)

Fred Hebert mononcqc@REDACTED
Fri Aug 12 14:34:16 CEST 2016

On 08/12, Richard McLean wrote:
>My main question is…
>Is this approach recommended or not ?
>(and if not are there any other recommended ways to achieve the same thing ?)

There's no recommendations around that. It is not the best thing in the 
world from the point of view of tracing and debug functions you may 
install in an OTP process throuhg the `sys' module, where that 
intermediary step will be lost.

>Does calling state functions directly break any OTP principles or lead 
>to any strange behaviour (eg. the main gen_fsm loop not knowing which 
>state it’s in +/- any corruption of centrally held StateData of the 
>main server loop) ?

There is no negative cost of doing it aside from this in the current 
case, as long as you can tolerate the out-of-order of messages. In this 
case, the FSM has been designed to be able to do it.

There's also the lack of traceability as mentioned above.

If you however use gen_statem (which is newer and I don't know if or 
when I'll update LYSE for it), you can make use of the `next_event' 
action to do the same thing; it allows you to specifically inject an 
event as the next one for instant handling. Say by returning:

    {next_state, listening, NewData, [{next_event, cast, done}]}

Which for gen_statem would let it do its event transition to listening 
while automatically re-triggering the `done' message sent as an 
asynchronous event, but right away. This gets rid of the obscurity 
around debugging functions and whatnot.

The bigger problem -- and this is a possibility both in gen_fsm and 
gen_statem -- happens if you rely on this mechanism for many events 
and/or transitions in an uninterrupted sequence.  The risk is eventually 
generating a chain of self-triggering events that never stop, and your 
FSM ends up mostly busy-looping itself for good, never handling external 


More information about the erlang-questions mailing list