[erlang-questions] Please correct my leeway on my first Erlang/OTP application

Garrett Smith g@REDACTED
Tue Mar 27 16:01:37 CEST 2012


Hi Aleksandr,

On Wed, Mar 21, 2012 at 2:05 AM, Aleksandr Vinokurov
<aleksandr.vin@REDACTED> wrote:
>
> Hello all,
>
> I'm quite a newbee in Erlang/OTP and will be very appreciated if you can
> point any wrong style or misunderstanding of the OTP in my first Erlang/OTP
> application.
>
> I've put it here https://github.com/aleksandr-vin/clustmea and will be glad
> to here any of your feedback.

I didn't look at everything -- that'd take quite a bit of time. But a
couple quick observations:

- (as Ladisklav mentioned) your project structure is not canonical --
I suggest using "rebar" to generate your project structure and build
your project (rebar isn't perfect, but it will serve you well for
this)

- Variables named "State2" or "Config2" are a sign that you should
think more carefully about your function

Here's an example from your project:

handle_call(#new{}, _From, State) ->
    {state, Configs1} = State,
    Cid = make_ref(),
    Configs2 = dict:store(Cid, [], Configs1),
    NewState = State#state{configs=Configs2},
    Reply = {ok, Cid},
    {reply, Reply, NewState}.

When I saw this I thought, "okay, this code needs to be cleaned up --
but what does it *do*?". I then spent several seconds squinting at the
code, sorting it out.

This version makes it obvious what's going on -- and you don't need to
enumerate different variable versions:

handle_call(#new{}, _From, State) ->
    Cid = make_ref(),
    {reply, {ok, Cid}, store_cid(Cid, State)}.

store_cid(Cid, #state{config=C}=State) ->
    State#state{config=dict:store(Cid, [], C).

"Single variable assignment" is a great feature! When you're tempted
to write using an imperative style -- long lists of instructions --
take a moment (or several moments) to think carefully about what
you're actually doing, and use functions to spell it out clearly.

Garrett



More information about the erlang-questions mailing list