Why do some people shun `if`?

Michael Truog mjtruog@REDACTED
Mon Aug 16 09:39:21 CEST 2021

If it is possible to use an "if" expression, it can result in better 
source code due to utilizing only guard expressions.  It is possible you 
may need to create an extra variable to use an "if" expression but that 
can help source code be more descriptive.  A "case" expression has more 
complex functionality by providing matching with guard expressions and 
it can result in more complex beam source code for the equivalent of an 
"if" expression (though it is likely that the compiler optimizations try 
to hide that when possible).

Why prefer guard expressions only?  Guard expressions are the only pure 
expressions, i.e., no side-effects (if you assume node() is returning a 
constant) so they help to completely isolate state, making the source 
code easier to understand, use and test.  It is common for people to 
avoid "if" expressions because they don't feel comfortable with them, 
but it is best to use them as much as possible.

On 8/14/21 2:44 PM, Michael P. wrote:
> I once stumbled over someone's Erlang style guide,
> they wanted no `if`.
> It was not very well explained why,
> and there was no obvious e-mail address,
> or I wanted to first do
> some thorough thinking about it.
> Now I have no more than this:
> Is if not merely "syntactic sugar" for
> a fun/0 with guarded clauses?
> ```
> Now_this_is = (fun If() when Guard_seq_1 -> Expr_seq_1
>                  %% On and on and on
>                   ; If() when Guard_seq_N -> Expr_seq_N
>                 end)(),
> % or:
> Worst = case true
>            of true when Guard_seq_1 -> Expr_seq_1
>             ; true when Guard_seq_2 -> Expr_seq_2
>           end.
> ```
> What could be perceived as wrong with `if`?
> ~M
> --
> But who will test the tests?

More information about the erlang-questions mailing list