Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java switch case - default vs explicit enumeration

I'm using Java 6.

Suppose I have an enum with 6 values, ordered A to F. About 4 of the values were handled the same. I could write it like this.

switch (whichType) {
    case A:
    case B:
    case C:
    case D:
        return task();
    case E:
        return someothertask();
    case F:
        return anothersomeothertask();
}

Or like this.

switch (whichType) {
    case E:
        return someothertask();
    case F:
        return anothersomeothertask();
    default:
        return task();
}

Null values will never reach this switch.

In terms of conciseness and clarity, the second approach is better. In terms of being explicit, I think the first approach is better.

Are there any other pros/cons of each approach?

Also, this simple question risks being a duplicate, but I tried and couldn't find it asked anywhere yet. I apologize if I haven't searched it good enough.

like image 291
Russell Avatar asked Jan 11 '11 03:01

Russell


2 Answers

Both are fine if that enum is absolutely, positively fixed at six values forever. Otherwise, think about what a possible seventh value for the enum might be. If E and F are the only two possible outliers with respect to this switch logic and any other value would fall in the same bucket as A through D, go ahead and use the default. Otherwise, you're safer to have a case per value.

like image 51
dkarp Avatar answered Sep 30 '22 02:09

dkarp


Suppose someone adds a value to the enumeration?

In some code I've got, there's this sort of construct:

switch(mediaType) {
    case typeA:
    case typeB:
    case typeC:
        DoGeneric();
        break;
    case TypeD:
        DoSpecial();
        break;
}

And the reason for that is so that if someone adds another possibility to the enumeration, it won't compile until you've looked at the places the enumeration is used and decided what needs to be done at that point. No chance of missing one and having a difficult-to-track-down bug.

like image 23
Anon. Avatar answered Sep 30 '22 04:09

Anon.