[erlang-questions] [erlang-questions 67] Problem using -(extends) with gen_server

Richard Carlsson carlsson.richard@REDACTED
Tue May 17 18:06:32 CEST 2011


On 03/28/2011 02:32 AM, Ken Robinson wrote:
> Hi All,
> I was trying to use -(extends) with gen_server. All the callback
> methods remained the same. The only exported function from the
> extended gen_server was the handle_call/3. What I found was it seemed
> to be failing at the init stage. Does gen_server work with -(extends)
> or should it be avoided. Does -(extends) only work with vanilla
> modules?
>

The (still experimental) inheritance declaration -extends(foo) can be 
used both in plain modules and in parameterized modules. There's nothing 
special about gen_server - I just tried doing what you described, and it 
works. There are some things to consider, though:

  - You need to have the same #state{} record declaration in both 
modules, if you are going to override one or more callbacks to do 
anything that reads or modifies the server state. Hence, put that 
declaration in a header file.

  - If you override one of the handle_call/handle_cast/handle_info 
functions, you should probably provide a catch-all clause that manually 
delegates any messages that you're not matching to the corresponding 
function in the base module, like this:

   handle_call(..., From, State) ->
      ...;
   handle_call(Request, From, State) ->
     ?BASE_MODULE:handle_call(Request, From, State).

(The BASE_MODULE macro is automatically defined when you use -extends.)

If you do this, things should work, but you may want to think twice 
about what it is you're creating here, and if inheritance is the right 
way to go. You won't be able to change the state record in the base 
implementation without affecting all processes that inherit from it, and 
you should at least have an "extension" field in the state record from 
start that can hold a proplist or similar so that the extended servers 
have somewhere to put any additional state they need to add.

    /Richard



More information about the erlang-questions mailing list