Reputation: 553
I recently came across the following example:
CommandKey key = command.getKey();
switch(key.ordinal()) {
case 1:
return IncidentType.StatusChange;
case 2:
return IncidentType.Notification;
...
Where the key is an enum.
Is there any reason why whoever wrote this did it as such, because this appears to make the code unnecessarily brittle; changes to the values of the enum list could potentially break the mapping logic and result in an incorrect return type.
The only possible benefit I can see is slight performance gains, which in the context of a server with high throughput could justify the adopted methodology.
Are any possible performance gains worth it, and are there any other benefits I am unaware of?
Upvotes: 1
Views: 197
Reputation: 311013
There's a good reason against it. The ordinals can change any time without breaking even binary compatibility. The names cannot so change at all.
A better solution would have been to build the returned values into the Enum
itself.
Upvotes: 2
Reputation: 77226
No, this shouldn't be used. The most charitable interpretation is that someone was blindly copying code from C or C++ with #define
s, but it should have been made idiomatic.
Furthermore, in a case such as outlined in the question (understanding that the real code could be more complicated), this would best be solved with a simple EnumMap
, which would be much more performant than any branch.
Upvotes: 2