4 ms·
Did I miss an explanation somewhere? Why are the `process_` functions referenced again in the default case? That has a code smell.
by delinka 10y ago
Did I miss an explanation somewhere? Why are the `process_` functions referenced again in the default case? That has a code smell.
- pdpi 10y agoDid you reach the end of the post? In the final version of the code, each of those functions is used exactly once.
- delinka 10y agoI did. But not requiring the `if` at all obviates the need for this `switch` abuse. Hence my question about its necessity.
- pdpi 10y agothe ifs allow the code to function correctly even if you forget to update this function with newly-added cases in the enums. The switch statement makes the known-cases behave O(1), while also bypassing unneeded validation.
- akkartik 10y agoThe known cases are O(1) even with an `if` -- all it's doing is a range check. Any performance benefit from this hack is miniscule at best. It may even end up confusing a compiler and making performance worse.
- pdpi 10y agoSure. I'm not arguing it's a good idea. It just serves as (somewhat forced) motivation for showing how to exploit this behaviour with switch labels, which is the real point of the post.
- drivers99 10y agoIf the number of options (CMD5, CMD6, etc) changes, he needs the code to not break if he adds them to the enum but doesn't doesn't extend the switch statement.
- pdpi 10y agoNot quite the same as Rust, but at least both GCC and Clang offer `-Wswitch-enum` which will cause non-exhaustive switches on enums to be raise warnings.
- deleted 10y ago[deleted]
- spott 10y agoThe first version references them to allow for a single point of refactoring to increase the number of command messages or status messages (the valid_xxxx_message() function call). He recognizes this as a not ideal and then refactors the code to have both the benefit of the jump table created by the switch statement and the benefit of the if statement (the single point of refactoring).
- delinka 10y agoI see now. If we add to the `enum`s and forget to update our `switch`, we still get the chance to process new commands, albeit with a minor performance hit. Personal opinion: Unit tests should be used to let you know when you forgot to add in new `case`s.