3 ms·
There's a few things potentially wrong (or right, in fact, depending on context - maybe you want them to fall through) with those switch statements, so I'm not
by zwischenzug 9y ago
There's a few things potentially wrong (or right, in fact, depending on context - maybe you want them to fall through) with those switch statements, so I'm not sure precisely what he's objecting to...
- onion2k 9y agoThe first example would be better as a simple if..else. The second example is doing an instanceof check on every case where it ought to be using switch(get_class($object)).
- meowface 9y agoI can't think of any case where `switch(true)` is what you actually want to do, barring some weird compiler workaround or hack or something. And the first one is akin to: if (data == 1) {} if (data == 2) {} if (data == 3) {} ... if (data == thevalueIactuallywant) { doSomething(); }
- plorkyeran 9y ago`switch (true)` is insane, but it does actually work as the author intended it to in PHP. It just evaluates each of the case statements in order until one evaluates to true, so it's equivalent to an if/else chain.
- tonmoy 9y agoActually in the hardware world I see switch(true) a lot. It is very useful for creating a priority encoder. For example you have 3 interrupts with priorities int0 > int1 > int2. Then this code is pretty clean and concise: Switch(true) { Case(int0): // Do stuff for interrupt 0 Case(int1): // Do stuff for interrupt 1 ...
- meowface 9y agoI stand corrected. Assuming no fallthrough, what are the advantages of this over chaining if and else-if? Just to look cleaner?
- consz 9y agoI believe the point is to explicitly take advantage of the fallthrough.
- meowface 9y agoWell, then it would just be chaining if statements.
- tonmoy 9y agoNot much, but I’d say it is more maintainable as well (you can change priority/get rid of the top one without affecting the following lines)
- aisamu 9y agoThe JS one doesn't work at all[1] - the cases are Strings, the input is a number. [1] - tested on Safari, but still...