Why do some people shun `if`?
Sun Aug 15 09:36:33 CEST 2021
After having worked with really complex systems in very large projects,
I've come to appreciate syntactic constructs signaling that nothing bad can
ever happen there.
As Craig points out, 'case' is much more flexible, but this also
potentially means that the expression evaluated by the case clause could
contain gremlins. In an 'if' clause, only guard expressions are allowed, so
only pure pattern matching - no side-effects allowed.
I think that's worth something.
On Sun, Aug 15, 2021 at 6:48 AM zxq9 <zxq9@REDACTED> wrote:
> 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:
> X > Y -> do_something();
> X = Y -> do_something_else();
> Y < Y -> do_yet_another_thing()
> This is *not* the same as a simpler boolean case
> case X > Y of
> true -> foo();
> false -> bar()
> `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.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the erlang-questions