Is there any significant reason to use the ordinal of an enum in a switch case, instead of using the enum?

184 Views Asked by At

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?

2

There are 2 best solutions below

1
user207421 On BEST ANSWER

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.

2
chrylis -cautiouslyoptimistic- On

No, this shouldn't be used. The most charitable interpretation is that someone was blindly copying code from C or C++ with #defines, 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.