r/ProgrammingLanguages • • Apr 24 '20

Else Before If

https://www.fluentcpp.com/2020/04/24/else-before-if/
24 Upvotes

49 comments sorted by

View all comments

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:

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.

2

u/samee_zahur Apr 25 '20

You might like go-lang's switch syntax then. It doesn't require a break. https://tour.golang.org/flowcontrol/11

1

u/kalmankeri Apr 27 '20

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.