I have a problem using switch statement when I tried to deal with a special situation. For example, I have 3 cases: A, B, C.
If a case has more than 2-3 statements it's bette(from point of view of readability and clean code) to extract them as separate methods:
switch (variable){
case A: handleCaseA(); break;
case B: handleCaseB(); break;
default: handleDefaultCase(); break;
}
Here u must use if statement
in this way because in switch
there are normally default
value also.
if (letter == 'A' || letter == 'B') { System.out.println("Statement 3 ");}
switch (letter) {
case 'A':
System.out.println("Statement 1 ");
break;
case 'B':
System.out.println("Statement 2 ");
break;
case 'C':
System.out.println();
break;
default:
System.out.println("You entered wrong value");
}
I often find introducing enum
s adds clarity. Here I imagine each enum
is an issue which can be resolved through a number of processes:
enum Issue {
A {
void handleIt () {
statement_1();
statement_3();
}
},
B {
void handleIt () {
statement_2();
statement_3();
}
},
C {
void handleIt () {
// Do nothing.
}
},
D {
void handleIt () {
A.handleIt();
B.handleIt();
}
};
abstract void handleIt();
}
Note here that you get the added benefit of being able to handle certain issues using the solutions of other issues (see my D
enum
).
i would recommend to define exactly what staments should be executed:
switch (variable){
case A:
statement_1();
statement_3();
break;
case B:
statement_2();
statement_3();
break;
}
for Update-3:
create methods for those 10 lines:
public void statement_1() {
//your 10 lines of code
}
if you're always executing statement_3, except for case C you can go with if/else-blocks as you wrote them.
but in my honest opinion: define EXACTLY what has to be done in which case if you have a small amount of cases. it is easier to read for others
You can do this:
switch (variable){
case A: do statement_1; do statement_3; break;
case B: do statement_2; do statement_3; break;
}
Why not nest the switch into the if statement? there is no-repeat code this way.
if(!C){
statement_3;
switch(variable){
case A:
statement_1;
break;
case B:
statement_2;
break;
}
or make use of both the if-statement and the switch?
if(!C){
statement_3;
}
switch(variable){
case A:
statement_1;
break;
case B:
statement_2;
break;