4 ms·
The key IMO is mentioned in one of the comments. > [lots of] switches on enums are a code smell Someone else also pointed out that a code smell doesn't mean s
by notacoward 5y ago
The key IMO is mentioned in one of the comments.
> [lots of] switches on enums are a code smell
Someone else also pointed out that a code smell doesn't mean something is always bad - only that it's likely to be bad. An enum that's rarely or never the subject of an if/switch check or pattern match is probably OK. For example...
* A type-safe and self-describing alternative to a boolean argument
* A scheduler priority or group
* A state in a state machine
OTOH, an enum that appears often in conditionals is likely to be error prone and classes or interfaces should be considered instead. But it's really all pretty context-dependent. The question is: which approach creates more coupling and/or requires more points in the code to be updated to remain correct when a new value is added?
- dragonwriter 5y ago> An enum that's rarely or never the subject of an if/switch check or pattern match is probably OK. If its never, then it is probably pointless. If it is rare, it is probably OK irrespective of language. If it is common, and it is a language with strong OOP support, and the conditionals repeat each other, you should probably consider whether you are using the enum as an inverted class and implementing common behavior that would make more sense in methods via redundant and hard to maintain conditionals on the enum. (If not, you should also consider if the enum is appropriate but the conditionals should be abstracted to a function.)
- notacoward 5y ago> If its never, then it is probably pointless. I disagree, because using an enum value as an index into an array or map (e.g. the scheduler-class example, or any other kind of grouping/routing) can still be useful even when there's no if/switch in sight. These patterns occur very frequently IMX. In many of these cases proper subranges would be even better and I wish more languages supported those, but an enum is still better than resorting to naked integers or (ick) strings to represent a small set of discrete values.
- Zababa 5y ago> OTOH, an enum that appears often in conditionals is likely to be error prone and classes or interfaces should be considered instead. That's surprising. Isn't the whole point of an enum to switch/match on it? > The question is: which approach creates more coupling and/or requires more points in the code to be updated to remain correct when a new value is added? As other people mentioned when talking about the expression problem (https://news.ycombinator.com/item?id=29306511 https://news.ycombinator.com/item?id=29306511), it depends. If you're going to add new types, enums are better. If you're going to add new operations, polymorphic objects are better. If you're going to add both, hope that you're doing Clojure or Haskell.