[erlang-questions] The gen server simplified (how it works)

Jeroen Koops koops.j@REDACTED
Wed Apr 20 15:09:03 CEST 2011

> The most common form of gen _server abuse I have seen (and I plead guilty
> of it myself) is attempting to turn it into something akin to a state
> machine. My rule of thumb is if your state record contains a field called
> state or something like it and you take different actions based on it, then
> it's time to re-factor into a gen_fsm. It's easy to get into this situation
> since things usually start simple and build up once more functionality is
> piled on.
I don't know about this -- I have written numerous gen_servers whose
state-record include a state-field (although I usually call it 'current'),
and events (calls, casts, infos) are handled differently depending on its
value. The reason for not using a gen_fsm is that very often, an event
should be handled in one way in one particular state, and in another way in
_all_ other states. This is easy to do using pattern-matching when using a
gen_server, but when using a gen_fsm you have no choice but to write out
every state/event combination, which can become pretty cumbersome.

On a related note, I have been moving away from using gen_servers all the
time. The reason for this is that in a gen_server, the state consists of
just the state term. In an arbitrary process, the state actually consists of
the process' entire call-stack, and it makes the flow in code such as the
almost proverbial:

idle() ->
        { Number, incoming } ->
        off_hook ->

... much easier to follow than when using a gen_server or gen_fsm.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20110420/d4721c5b/attachment.htm>

More information about the erlang-questions mailing list