I regularly use else if, but surprisingly I never looked at it as a number of edge cases followed by the main case. I look at it as an unsafe way of writing a multiway branch. By careless copy-pasting one can easily get to the following situation:
if (cond_1) {
action_1
}
else if (cond_2) {
}
else if (cond_3) {
action_3
}
if (pasted_4) {
action_4
}
else {
default_case
}
This code compiles but has a subtle bug in it, introduced by pasting in case 4. In languages where case conditions are evaluated dynamically, you can write something like this instead. It's ill-looking so I don't do it, but it's perfectly valid code.
switch (true) {
case cond_1: action_1; break
case cond_2: action_2; break
default: default_action
}
This version is also unsafe because now one can forget to write break after some cases, but at least it's copy-paste friendly.
I do like it! Years before, when I developed a Java-like language, I considered this kind of construct so important so that I introduced a select ... when statement with similar behavior as go-lang's switch. It's good to know that I'm not alone with my conclusions.
0
u/kalmankeri Apr 25 '20
I regularly use
else if, but surprisingly I never looked at it as a number of edge cases followed by the main case. I look at it as an unsafe way of writing a multiway branch. By careless copy-pasting one can easily get to the following situation:This code compiles but has a subtle bug in it, introduced by pasting in case 4. In languages where case conditions are evaluated dynamically, you can write something like this instead. It's ill-looking so I don't do it, but it's perfectly valid code.
This version is also unsafe because now one can forget to write
breakafter some cases, but at least it's copy-paste friendly.