Reputation: 914
I'm learning Erlang, and I saw an example of "Safe Usage"
this is the example of preferred "safe usage"
better(N) ->
X = case N of
1 -> 1;
_ -> 0
end,
X.
and also an example of safe but bad
bad(N) ->
case N of
1 -> X =1;
_ -> X = 0
end,
X.
I understand the functionality of those two (look the same to me), but I couldn't understand what's make the first function better, and the second bad?
Upvotes: 2
Views: 187
Reputation: 20004
In the first example, X
is bound only once. Should you ever wish to change the case
expression to add a new clause, the binding of X
will remain the same. But with the second example, it's too easy to forget to bind X
in every new case
clause, and so you wind up with compilation errors about unsafe variables, not to mention your code is more verbose than necessary and is thus harder to read.
Another alternative to using case
like this is to use multiple function clauses instead:
best(1) -> 1;
best(_N) -> 0.
This is clearer than either of the bad
or better
functions and is more easily maintained.
Upvotes: 7