3 ms·
It's weird, and even harmful in many cases. A modern goto of sorts: it has performance benefits [1], but not overall readability ones. switch (x) {
by paulddraper 9y ago
It's weird, and even harmful in many cases.
A modern goto of sorts: it has performance benefits [1], but not overall readability ones.
switch (x) {
case 0:
doThing1();
break;
case 1:
doThing2();
break;
default
doThing3();
}
vs
if (x == 0) {
doThing1();
} else if (x == 1) {
doThing2();
} else {
doThing3();
}
This somewhat unsafe form of switch-case made it into C, Java, C#, and JavaScript, and cases the great iOS SSL bug of 2014. [2]
[1] https://en.wikipedia.org/wiki/Duff%27s_device https://en.wikipedia.org/wiki/Duff%27s_device
[2] https://nakedsecurity.sophos.com/2014/02/24/anatomy-of-a-goto-fail-apples-ssl-bug-explained-plus-an-unofficial-patch/ https://nakedsecurity.sophos.com/2014/02/24/anatomy-of-a-got...
- archagon 9y agoI use it because if your switch is exhaustive, it's nice that the compiler can tell you exactly which parts of your code need to be updated when you add cases to an enum. (Also, in Swift, fallthrough is opt-in instead of opt-out, which is great.)
- paulddraper 9y agoScala pattern matching is the same. Both are less easy to misuse than C switch.