DEV Community

Discussion on: I've never become overly convinced that switch statements are that much cleaner than `if else if else if else if else`

Collapse
 
cubiclebuddha profile image
Cubicle Buddha

I don’t think fallthrough in a switch case is ever appropriate due to the potential for buggy side effects. I describe that in this article and I’d love to hear your thoughts on if you agree: dev.to/cubiclebuddha/is-defensive-...

Collapse
 
sergix profile image
Peyton McGinnis

I absolutely agree with your point. default/else cases should be used for error handling in most instances.

However, I should have clarified, so the fault is on my behalf, but when I said "switch 'fallthrough'", I meant when you have a situation like the following:

switch (x) {
  case 'a':
  case 'b':
    return 1;
  default: throw(); break;
}
Enter fullscreen mode Exit fullscreen mode

Here, it's easier (for me, at least) to see which possible values return 1 than this:

if (x == 'a' || x == 'b') {
  return 1;
} else {
  throw();
}
Enter fullscreen mode Exit fullscreen mode

I'm probably missing another thing you can do with if statements to make it more clear. But, after all, this is #healthydebate... So tell me how I'm wrong! :P

Thread Thread
 
cubiclebuddha profile image
Cubicle Buddha

Those examples your provided look great to me. I just don’t like when code assumes that there will never be a new case. I explain that a little better in my article. But it looks like you’re covering the known cases. So great work! :)