[erlang-questions] Parameterized module idioms

Bob Ippolito <>
Sat Apr 17 02:06:32 CEST 2010


On Fri, Apr 16, 2010 at 4:56 PM, Garrett Smith <> wrote:
> On Fri, Apr 16, 2010 at 1:09 PM, Mark Fine <> wrote:
>> Is there a cleaner, more idiomatic way to use object-like parameterized
>> modules:
>>
>> -module(echo, [PID]).
>> -behaviour(gen_server).
>> -export([start_link/0, echo/1]).
>> -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2,
>> code_change/3]).
>>
>> start_link() ->
>>    case gen_server:start_link(?MODULE:new(undefined), [], []) of
>>        {ok, Pid} ->
>>            {ok, ?MODULE:new(Pid)};
>>        Else ->
>>            Else
>>    end.
>>
>> echo(What) ->
>>    gen_server:call(PID, {echo, What}).
>>
>> handle_call({echo, What}, _From, State) ->
>>    {reply, What, State}.
>>
>> init([]) -> {ok, []}.
>> handle_cast(_Msg, _State) -> undefined.
>> handle_info(_Info, _State) -> undefined.
>> terminate(_Reason, _State) -> undefined.
>> code_change(_OldVsn, _State, _Extra) -> undefined.
>>
>> 17> {ok, E} = (echo:new(undefined)):start_link().
>> {ok,{echo,<0.82.0>}}
>> 18> E:echo("hello, world").
>> "hello, world"
>> 19>
>>
>
> I realize there are some fans of parameterized modules. I'm wondering
> though if this:
>
>  E:echo("hello")
>
> provides enough payoff over this:
>
>  echo(E, "hello")
>
> to justify the effort.
>
> I come from an OO background myself, but for whatever reason, the
> second form doesn't bother me. It may be that it's so endemic in
> Erlang that I've gotten used to it.

Technically speaking the difference is:

E:echo("hello") vs. some_module:echo(E, "hello")

The biggest reason I've seen to use parameterized modules is that you
could have a different module that implements the same interface, e.g.
sets and gb_sets and you could change which one you're using without
changing any of the code that consumes it.

I would definitely change the original code to use two modules, one
module to do the start_link stuff, and another module to actually
implement the interface.

-bob


More information about the erlang-questions mailing list