4 ms·
Never knew enums are even considered to be code smell Linters can/should already detect when a switch on enum doesn't handle all cases
by trinovantes 5y ago
Never knew enums are even considered to be code smell
Linters can/should already detect when a switch on enum doesn't handle all cases
- IggleSniggle 5y agoExactly. Indeed, the whole point of using switch+enum is frequently to get exhaustiveness checking on your conditional!
- jeffbee 5y agoAside from linters, at least some very common C++ compilers will refuse to compile a non-exhaustive switch statement.
- todd8 5y agoDo you mean when specific flags are passed to the compiler? I wasn’t aware of that. C++ has defined behavior for non-exhaustive switch statements, just like a non-exhaustive if statement (that is an if statement missing an else clause).
- ahartmetz 5y agoCompilers have (optional - it's kinda good practice to enable them though) warnings about things that are perfectly within spec and not undefined behavior, but usually a bad idea. A switch statement with a default: label is exhaustive. The warning is only about switches without a default. There is also a warning about exhaustive switches with a default. Makes sense - the first is apparently supposed to handle all the cases, but doesn't. The second is apparently supposed to handle some cases and not some others, but given that it's actually exhaustive, any enumerator added later should probably get its own label instead of falling under the previously unused default label.
- gwbas1c 5y agoOr in a unit test
- Lutger 5y agoFor some languages, like D, that can also be expressed in the language itself: https://dlang.org/spec/statement.html#final-switch-statement https://dlang.org/spec/statement.html#final-switch-statement
- klyrs 5y agoMe neither, but now I'm picturing a horrible mess of an IOCCC entry that abuses enums beyond all reason...
- chris37879 5y agoThey're only a code smell in languages that treat them poorly. Most modern languages have enums as just a matter of course for the language. I'm using Dart rather a lot these days for Flutter, and I absolutely love their enums. I can extend one and use it like a pseudo type union, or for a thing like `Environment.development`, I can extend that so that any `Environment` variable automatically has properties like `apiUri` or `name` or whatever other thing that changes per environment, but the set of them is still well known ahead of time.