[erlang-questions] [clarify] Variable binding in case clause and coding style

Jay Nelson jay@REDACTED
Mon Mar 10 16:42:30 CET 2008

Christian S wrote:

 > I rather rewrite it to this:
 > case Endianness of
 >   big ->
 >     <<A:1/unit:32-big, Rest/binary>>,
 >     do_something(A,Rest);
 >   little ->
 >     <<A:1/unit:32-little, Rest/binary>>,
 >     do_something(A,Rest)
 > end.

It is simply easier to understand and not misinterpret.  Lexical
scoping for teh win.

If you don't like the repetition of function names, you can return a  
new structure which gives fresh variable references and avoid using  
the ones created in the case branches:

{Integer, More} = case Endianness of
                                             big ->
                                                 {A, Rest};
                                             little ->
little, Rest/binary>>,
                                                 {A, Rest}
do_something(Integer, More).

The main point is that it is error prone to rely on all branches of a  
case to set variables which are used later.  Better to make it  
explicit and let the compiler help you notice when one is missing.


More information about the erlang-questions mailing list