Why do some people shun `if`?
Jesper Louis Andersen
Sun Aug 15 15:15:02 CEST 2021
On Sat, Aug 14, 2021 at 11:45 PM Michael P. <empro2@REDACTED> wrote:
> I once stumbled over someone's Erlang style guide,
> they wanted no `if`.
There are uses for the if...end construct in Erlang. The reason you often
shun it is because it occurs quite rarely in a language where you have a
proper case...end matching construct. So to avoid newcomers to fall into a
trap of using if all the time, you write it down in the style guide. In
reality, style can be broken for improved readability, but it takes some
knowledge to know exactly when.
The deeper underlying problem is that of "boolean blindness". A value that
is true/false doesn't tell you *why*. If you write a function such as
empty() -> true;
empty([_|_]) -> false.
you know that the list is empty, but you don't get to know it's structure.
Whereas with a match
case L of
 -> ...;
[H|T] -> ...
you *do* know the structure in each variant clause, and you also have
convenient bindings for the head and tail. If-constructs will have you
analyze the structure after you hit a branch, whereas pattern matching
allows you to make that analysis up front. Erlang terms are ripe for
scrutiny, so as a result, you'll find much more use of case than if.
That said, and what Ulf alludes to: there are always exceptions to the rule.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the erlang-questions