Avoid redundancy of operator conclusions when several cases do the same thing?

I have a few cases in a switch that does the same thing, for example: (this is written in Java)

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

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

+7
source share
4 answers
 case 1: case 2: case 3: aMethod(); break; case 4: anotherMethod(); break; 

This works because when it happens, for example, case 1 (for example), it goes to case 2 ( break statement), which then goes to case 3.

+14
source

Of course, you can allow the sections of the case section for 1 and 2 to “fail” in section 3, and then break from the switch after that:

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

Below is the best you can do

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

He called the template "fail":

 case 1: // fall through case 2: // fall through case 3: aMethod(); break; case 4: anotherMethod(); break; 
+3
source

All Articles