Reusing code in a switch statement (Java)

I would like to use the operator switch, but I cannot build it without duplicate code or with the help of the attached operator if. Is there any way around this?

I have 5 cases, and for all but one of them, I would like to perform a certain action. Therefore, with the help of the instruction, switchI can simply do:

switch(x) {
case A:
    foo();
    break;
case B:
case C:
case D:
case E:
    bar();
    break;
}

Easily. But the difficulty is that I also need to perform another separate action for each of them, so I cannot use the end-to-end case function. Therefore I am reduced to

switch(x) {
case A:
    foo();
    baz(0);
    break;
case B:
    bar();
    baz(1);
    break;
case C:
    bar();
    baz(2);
    break;
case D:
    bar();
    baz(3);
    break;
case E:
    bar();
    baz(4);
    break;
}

which smells to me of having to repeat bar()every time, or

switch(x) {
case A:
    baz(0);
    break;
case B:
    baz(1);
    break;
case C:
    baz(2);
    break;
case D:
    baz(3);
    break;
case E:
    baz(4);
    break;
}
if (x != A) { bar(); }

- , , switch, if.

, ,

Map<X, Integer> m = new HashMap<X, Integer>();
m.put(A, 0);
m.put(B, 1);
m.put(C, 2);
m.put(D, 3);
m.put(E, 4);

if (m.get(x) == 0) {
    foo();
} else {
    bar();
}
baz(m.get(x));

, . ( , .)

?

+4
3

x ? .

enum Employee {
    SENIOR {
        @Override
        public int salary() {
            return 60;
        }
    },
    JUNIOR {
         @Override
         public int salary() {
            return 40;
         }
    };

    public abstract int salary ();
}

  employee.salary();

, .

; , , . ... . "Employee" "foobar".

   private final boolean flag;
   Employee(int flag) {
       this.flag = flag;
   }

   public int method() {
       if(flag) {
            secondMethod();
       }
       alwaysMethod();
   }
+11

pass x baz :

switch(x) {
case A:
    foo();
    break;
case B:
case C:
case D:
case E:
    bar();
    baz(x); // < --- 
    break;
}


void baz(SomeEnum val){
 switch(val) {/* ...*/}
}
+1

I assume your cases are fixed, so you can use an enumeration and just exclude one of them.

public enum MyCase {
   A, B, C, D, E;
}

and condition

MyCase x;
...
if MyCase.A.equals(x) {
    foo();
} else {
    bar();
}
baz(x);
// or if the oridnal value is required
baz(x.ordinal);
0
source

All Articles