Why do some people shun `if`?

zxq9 zxq9@REDACTED
Sun Aug 15 06:48:39 CEST 2021


Hi, Michael.

On 2021/08/15 6:44, Michael P. wrote:
> I once stumbled over someone's Erlang style guide,
> they wanted no `if`.
> It was not very well explained why,
...
> Is if not merely "syntactic sugar" for
> a fun/0 with guarded clauses?

The main reason people dislike `if` is that it applies to boolean 
comparison situations where `case` provides for a much more interesting 
semantic for branching. `if` is most often best used in situations where 
you have a *range* of values you want to completely cover:

   if
      X > Y -> do_something();
      X = Y -> do_something_else();
      Y < Y -> do_yet_another_thing()
   end

This is *not* the same as a simpler boolean case

   case X > Y of
     true  -> foo();
     false -> bar()
   end

`if` enables more complex ranges and the drop-through nature of the 
various clauses are occasionally very useful in reducing some evaluation 
of complex checks that tend to create even messier and more complex code 
to something easy to read.

You can still always do the same thing with a `case` using guards, 
though -- and as you mentioned you *could* do the same with funs, but 
that's a bit crazy as you're invoking the lambda machinery for really no 
reason as there is motivation to create and execute a function in place 
when you just want to perform a simple comparison.

In Erlang it is much more common to use `case` for just about everything 
and most programs don't have a single `if` in them at all unless they 
are written by people coming to Erlang from another language that only 
has `if` (and then they wind up often misunderstanding the semantics of 
Erlang's version of `if`, so you see the default `true` clause pop up, 
which makes the newcomer think "this is silly, why does Erlang's `if` 
work this way?" because using `if` that was *is* silly in most cases).

Anyway... generally speaking `case` is much more powerful than `if`, and 
`if` has a very niche use case for which it is a very concise way of 
doing comparisons within a function body that carries some context you 
need to involve in the `if` test clauses that would otherwise be 
cumbersome to pass along to a special function whose only job was to 
check something in guards.

-Craig


More information about the erlang-questions mailing list