3 ms·
I do this a lot too. Often long chains of if statements are really performing a manual mapping from one set of values to another. Just keep a map and perform
by cle 10y ago
I do this a lot too. Often long chains of if statements are really performing a manual mapping from one set of values to another. Just keep a map and perform a lookup! Easier to read, easier to change, and easier to extend since the mapping is a data structure instead of code.
- adrianratnapala 10y agoEfficiency-wise I agree, but if I don't care about efficiency then I often prefer an if-chain (or better still, a switch-case). The point is that the desired mapping is known not just at compile time, but is explicitly known to the programmer. So it is clearer if it right there in the executable code rather than hidden away in some moving part (the mapping data structure).
- userbinator 10y agoswitch-case is often compiled to a table lookup, but if your expressions are constant (at least for the part where the table is being used), the latter is definitely less verbose. So it is clearer if it right there in the executable code rather than hidden away in some moving part (the mapping data structure). Following several levels of nested if/else is "clearer" than going to the right array index? I don't know what you mean by "hidden away in some moving part".
- adrianratnapala 10y agoIf you have several levels of nested if-else (as opposed to a linear chain of "if"-"else if"), then you probably need a more complicated table than a linear array. The moving appart that gets hidden away is the table (or more often, Hack mandictionary) that is stored somewhere in memory. If you are lucky, it is stored statically. It is never defined in quite the same place as the decision that it implements.
- cle 10y agoPersonally I don't like switch statements at all, especially the ones that require manual control flow management. I can vividly remember multiple bugs over the years caused by forgetting to add "break" to a switch statement. Unless you're optimizing for performance (which is rare in my domain), control-flow statements are a smell and should be avoided. Each branch has some "implicit" state that is being fragmented and has to be manually managed by the programmer.
- bbcbasic 10y agoC# will optimise something like >7 items in a switch statement to a lookup. Funny how this doesn't play nice with code contracts!