[erlang-questions] Avoiding boilerplate code when using gen_server

Joe Armstrong erlang@REDACTED
Wed Mar 21 21:01:09 CET 2012

On Wed, Mar 21, 2012 at 8:28 PM, Garrett Smith <g@REDACTED> wrote:
> On Wed, Mar 21, 2012 at 2:21 PM, Joe Armstrong <erlang@REDACTED> wrote:
>> On Wed, Mar 21, 2012 at 4:29 PM, Garrett Smith <g@REDACTED> wrote:
>>> Here's a "gen_server" equivalent in e2:
>>> https://github.com/gar1t/e2v2/blob/master/examples/ping/src/ping_server.erl
>> That's nice - but one could with a little thought and a few conventions
>> make this even shorter. Something like:
>>    -module(ping_service).
>>    -behavior(e2_service).
>>    -interface([ping/0]).
>>    ping(_From, State) -> {reply, pong, State}.
>> And just let all undefined values default to sensible values.
>> As in your version you could use
>>    init() -> State to prime the state
>> A counter would just be:
>>    -module(counter).
>>    -behaviour(e2_service).
>>    -interface([inc/1, dec/1, get/0])
>>    init() -> 0.
>>    deposit(_From, X,N) -> {reply,ack,N+X}.
>>    withdraw(_From,N) ->
>> {reply,ack,N-1}.
>>    get(_From, N) -> {reply,N,N}.
> Joe, in this case, what would the "interface" documentation look like?

It should expose the interface from the external point of view.
The ping_service interface is.

   ping_service ? ping => pong

meaning if you send the ping service a 'ping' message it will reply
with a 'pong' message.

All the stuff *inside* the implementation (the From, and State)
is basically junk (as seen from the outside) and should not be
in seen in the interface type signatures.

Re: your comments on parse_transforms - Yes and No :-)

In my experience very few people break open abstractions to see how
things work if they do in fact work. Very few people seem to
look inside the gen_server to see how they work and even fewer modify
gen_server etc.

How many people have changed error_handler.erl ? I designed it
specifically so that you could drop in you own replacement. A lot
of the things in the code server/io system etc are designed with hooks
so they can be customised later - but virtually nobody does this.

Probably a case of 'if it ain't broke don't fix it' - all this would argue
in favor of a fixed set of boiler plate transformations aimed at truly
minimalistic code for the commonest use cases.


> Garrett

More information about the erlang-questions mailing list