[erlang-questions] Parameterized module idioms

Bob Ippolito bob@REDACTED
Sat Apr 17 03:09:37 CEST 2010


On Fri, Apr 16, 2010 at 6:06 PM, Garrett Smith <g@REDACTED> wrote:
> On Fri, Apr 16, 2010 at 7:06 PM, Bob Ippolito <bob@REDACTED> wrote:
>> On Fri, Apr 16, 2010 at 4:56 PM, Garrett Smith <g@REDACTED> wrote:
>>> On Fri, Apr 16, 2010 at 1:09 PM, Mark Fine <mark.fine@REDACTED> 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")
>
> Yup, sorry, I did deceptively simplify my example :)
>
>> 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've found that custom behaviors also work well for this, at least for
> interfaces to processes.

Yeah well, processes can do everything that parameterized modules can
do, except perform well if you're trying to do a lot of concurrency ;)

-bob


More information about the erlang-questions mailing list