Search code examples
javaenumsordinalordinals

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


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?


Solution

  • 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.