Best practices: get/put

Pascal Brisset <>
Mon Jan 30 02:06:22 CET 2006


 > The best practices document says that one should avoid using get/put do 
 > store data in the process dictionary. I'm guessing that in gen_servers, 
 > that information should actually be stored in the various State 
 > parameters/returns, right?

Some people have suggested using the process dictionary with a
strict "single-assignment" or "write-once, read-many" policy.
I find this acceptable and useful in some cases, e.g. when the
state of a gen_server is so simple that encapsulating it in a
record together with persistent configuration data would add
too much syntactic overhead:

 | init(Config) ->
 |   put(foo, Config#config.foo),
 |   put(bar, Config#config.bar),
 |   {ok, queue:new()}.
 | 
 | handle_call(Call, From, Queue) ->
 |   R = f(Call, get(foo)),
 |   X = g(Call, get(bar)),
 |   {reply, R, queue:in(X,Queue)}.

The idea is to have some kind of process-local naming scope.
Actually I would rather do it with a closure, if this didn't
deprive me of most of the benefits of using a gen_server:

 | server(Config) ->
 |   Foo = Config#config.foo,
 |   Bar = Config#config.bar,
 |   loop(queue:new(), fun(Call,From,Queue) ->
 |          R = f(Call, Foo),
 |          X = g(Call, Bar),
 |          {reply, R, queue:in(X,Queue)}
 |        end).

-- Pascal




More information about the erlang-questions mailing list