Switch on True (2008)
jayjohnston.com
jayjohnston.com
Even in languages with proper pattern matching it makes no sense to do something like the following instead of if/else:
match x {
x if x < 20 => foo(x),
x if x >= 20 => bar(x),
...
}
Avoiding complex if/else chains is a good idea, but replacing them with the same thing, only spelled differently , is not the way to do it.In Elixir, I find myself using:
if x do
<blah>
else
<bleh>
end
only in situations where I'm almost certain I won't end up having more cases, and in practice I tend to limit myself even to conditionals that are short, where I can do: if x, do: y, else: z
But in many, many situations I go for: case x do
<condition 1> -> <stuff>
<condition 2> -> <other stuff>
end
because it looks cleaner, and because I often end up adding another condition.Furthermore, there's also 'cond', which looks similar. using 'case' and 'cond' often just seems clearer to me over having a quite different syntax in the one situation where there's only two options ('if').
(not having to 'break' makes a big difference though)
I like having functions with expressive names to encapsulate/hide complexity, and to comment what I'm doing. If it is not obvious why "20" is such a big deal in your code, then that's where I would trip up.
I don't mind having a few ifs if they look like this:
if (isHoliday()) { }
else if (isWeekend()) { }But the negative is that you've added the requirement to always remember to include "break;" after each block. The code is prettier but also more fragile. This type of vigilant programmer discipline required to keep the code error-free (especially across multiple programmers) is not easy. Missing "break" statements causing unintended fallthrough are common bugs discussed in many "traps & pitfalls" books/blogs.
The "else if" while not as vertically aligned, includes the invisible "break;" for free.
(Side note that some languages like C#'s and Rust's switch statement don't have fallthrough behavior -- but this article uses PHP which does.)
For example, I have some Agda code (totally unreadable to anyone who didn't write it, i.e. anyone who isn't me) where I switch on whether a+1 is less than, equal to, or greater than x+1, as part of the inductive step in an implementation of the division algorithm, rendering a number into a quotient and a remainder on division by another number. The type system guarantees that I haven't missed any cases. (https://github.com/Smaug123/agdaproofs/blob/9e22ba78f5446ce7...)
if (false){
} else if ($var=='possible value 1') {
echo $var;
} else if ($var=='possible value 2') {
error_log($var);
} else {
// do nothing
}
Now we just to find somewhere where it would be a good idead...This is an ugly port of Lisl's "cond".
1. Skeuomorphic torn-paper edge at the bottom
2. Loud background image on the body
3. Text is unreadably small on mobile
4. php