[erlang-questions] Newbie question about Erlang style

Gleber <>
Wed Feb 27 23:31:03 CET 2008


On Wed, Feb 27, 2008 at 10:40 PM, Håkan Stenholm
<> wrote:
> 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
>  > 
>  > http://www.erlang.org/mailman/listinfo/erlang-questions
>  >
>  >
>  _______________________________________________
>  erlang-questions mailing list
>  
>  http://www.erlang.org/mailman/listinfo/erlang-questions
>

Please note that:

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

could be written as

foo2(foo) -> 1;
foo2(bar) -> 2.

IMHO it is more readable.

-- 
Gleb Peregud
http://gleber.pl/

"Only two things are infinite, the universe and human stupidity, and
I'm not sure about the former."
--  Albert Einstein


More information about the erlang-questions mailing list