Java switch case - default vs explicit enumeration

I am using Java 6.

Suppose I have an enumeration with 6 values, ordered A to F. About 4 values ​​were processed 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 that.

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

Null values ​​will never reach this switch.

In terms of brevity and clarity, the second approach is better. As for the explicit, I think the first approach is better.

Are there any other pros / cons of each approach?

Also, this simple question may be duplicate, but I tried and could not find it anywhere. I apologize if I did not look for him well enough.

+5
source share
5 answers

, , . , . E F switch, , A D, default. case .

+7

, - ?

, , :

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

, - , , , , , . .

+3

, , , . , .

, , , . . . , - , , , ( task() ). .

(, switch ), , , . ( , ), /.

+2

default, , . , , , , .

switch (whichType) {
    case A:
    case B:
    case C:
    case D:
        return task();
    case E:
        return someothertask();
    case F:
        return anothersomeothertask();
    default:
        throw new IllegalArgumentException("Encountered unknown type: " + whichType.name());
}
+2

If you are writing some kind of business scenario and you expect the code to live and be supported (by some other person) for many years, go with option 1. There is nothing wrong with option 2, it’s short and clear, but, speaking of maintainability, I think that option 1 wins - especially if the cases are connected with some kind of business logic. It will be much easier for a technical engineer to read it.

0
source

All Articles