Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid Switch statement redundancy when multiple Cases do the same thing?

I have multiple cases in a switch that do the same thing, like so: (this is written in Java)

 case 1:
     aMethod();
     break;
 case 2:
     aMethod();
     break;
 case 3:
     aMethod();
     break;
 case 4:
     anotherMethod();
     break;

Is there any way I can combine cases 1, 2 and 3 into one case, since they all call the same method?

like image 563
Zargontapel Avatar asked Oct 19 '12 00:10

Zargontapel


People also ask

Can you have multiple cases in a switch statement?

A switch statement includes multiple cases that include code blocks to execute. A break keyword is used to stop the execution of case block. A switch case can be combined to execute same code block for multiple cases.

Should you avoid switch statements?

Therefore nested switch statements should be avoided. Specifically, you should structure your code to avoid the need for nested switch statements, but if you cannot, then consider moving the inner switch to another function.

What will happen if the switch statement did not match any cases?

If no cases are matched and default is not provided, just nothing will be executed. Save this answer.

Which of the following statements is used to avoid fall through in switch-case?

In practice, fallthrough is usually prevented with a break keyword at the end of the matching body, which exits execution of the switch block, but this can cause bugs due to unintentional fallthrough if the programmer forgets to insert the break statement.


1 Answers

case 1:
case 2:
case 3:
    aMethod();
    break;
case 4:
    anotherMethod();
    break;

This works because when it happens to be case 1 (for instance), it falls through to case 2 (no break statement), which then falls through to case 3.

like image 97
Ted Hopp Avatar answered Oct 20 '22 06:10

Ted Hopp