Hi Michal,
Isn't a developer's first mission to write working, readable, tested and maintainable code ? Optimizing code come later.
Let me quote some some text from the post you mention about "==" usage:
enums
are Objects. For all other Object types the standard comparison is .equals()
, not ==
This one is really important and is the core reason why equals should be used.
It works: Until you need to replace an enum with a class as part of a refactoring. Good luck finding all the code using == that breaks.
Indeed it works, Enums equality can be verified using ==, by the way that's what is done under the hood by all (most?) VMs, but it is done for optimization reasons not for readability / maintainability reasons, and it is hidden to the enduser.
It's faster: Even if true (questionable), there's that Knuth quote about premature optimization.
Same as previous comment. Such low level optimizations should be left to the compiler + JIT compiler. And seriously "how much" faster ? with a -client or -server ? for how many hits ? And I would like to ask people doing such low level optimizations if they are sure that all their algorithms are so perfect they need to do such kind of optimization (I'm pretty sure JIT does them as well anyway)
Safer at run-time: "Safe" is not the first word that springs to mind if the use of == is the only thing separating you from a NullPointerException.
Agree, and SQ can help you write correctly the equals statement to make sure that NPE will never be thrown. You can also use @NonNull which makes the code more readable and understandable (and thus maintainable, ... and more secure in the end)
Safer at compile time: Not really. It can guard you from the rather elementary mistake of comparing the wrong types, but again, if that's how dumb your programmers are, "safe" is the one thing you're not.
I Agree (at least partially... it's not about being dumb but about making stupid mistakes anyway, but well... sleepy people can also use = instead of == in other situations)
All in all, yes, you can check enums' equality with == but it is not worth the impact on readability and maintainability.
In other words I would not change your example @Ann.
Michel