4 ms·
I seem to remember the Martin Fowler advice that this apparently cited being slightly more nuanced, and it’s not totally wrong. If you have a simple enumerator
by aardvark179 5y ago
I seem to remember the Martin Fowler advice that this apparently cited being slightly more nuanced, and it’s not totally wrong. If you have a simple enumerator and many switch statements depending on it then it is quite error prone if you have to add a value (depending on your language it may even be a silent failure), but a class will force you to implement the bits of behaviour you need as methods, and gives a good template for when you add another subclass. It’s not always the right thing to do, you’re trading the flexibility for others to add new types for the old flexibility of it being easy to add new behavioural decision based on a fixed set of types.
I think in a lot of cases it’s definitely worth stopping and thinking, and making sure you are implementing the right thing if you find yourself using enums heavily, or using a class hierarchy as an enumerator replacement.
- dwaltrip 5y agoIf I’m understanding correctly, languages like rust avoid that problem by throwing a compile error when a match statement doesn’t cover all possible cases. Of course, a catch-all would then somewhat reintroduce the problem.
- aardvark179 5y agoYes. The problem you then have is that adding additional values to the enum then either breaks compatibility or relaxes that guarantee. Since Java tries to run old code for as long as possible the only option for switch statements is to ensure there is a fallback so that you at least know there is a problem.