[erlang-questions] Newbie question about Erlang style

Håkan Stenholm hokan.stenholm@REDACTED
Wed Feb 27 22:40:46 CET 2008


Convey Christian J NPRI wrote:
> Is there any non-aesthetic reason prefer one of the following approaches over the other?
>
>
> if Foo  -> X = 1;
>    true -> X = 2
> end
>
> vs.
>
> X = if
>    Foo  -> 1;
>    true -> 2
>    end
>
>   

* "X = if .... end" is generally less cluttered as the variable name 
isn't repeated several times, which can be tedious if the variable name 
is long.

* This also avoids issues with forgetting to declare the variable in 
certain case/if branches.

* It makes it simpler to see where new variables are introduced, as they 
will always appear at the beginning of lines.

* The "Variable/Pattern = expression" style makes the code more 
consistent with for example the look of function calls. If/when you need 
to refactor your expression part into a separate function, there will 
then be no need to move variables around:

foo(V) ->   %% ugly style
    case V of
       foo -> X = 1;
       bar -> X = 2
    end,
    ... X ...

vs

foo(V) -> %% clean style, moving code to foo2/1 is trivial
    X = case V of
       foo -> 1;
       bar -> 2
    end,
    ... X ...


=>   %% refactored version, compare amount of code that needs to be 
moved around

foo(V) ->
    X = foo2(V),
    ... X ...

foo2(V)
    case V of
       foo -> 1;
       bar -> 2
    end.



* It's the way erlang code is usually written.






> Thanks,
> Christian
>
> Christian Convey
> Scientist, Naval Undersea Warfare Centers
> Newport, RI
>
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://www.erlang.org/mailman/listinfo/erlang-questions
>
>   



More information about the erlang-questions mailing list