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

后端 未结 4 1031
轮回少年
轮回少年 2021-02-14 05:47

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();
     b         


        
相关标签:
4条回答
  • 2021-02-14 06:39

    Sure, you can allow case clause sections for 1 & 2 to 'fall through' to clause 3 and then break out of the switch statement after that:

    case 1:
    case 2:
    case 3:
         aMethod();
         break;
    case 4:
         anotherMethod();
         break;
    
    0 讨论(0)
  • 2021-02-14 06:46
    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.

    0 讨论(0)
  • 2021-02-14 06:47

    It's called the "fall through" pattern:

    case 1:  // fall through
    case 2:  // fall through
    case 3: 
       aMethod(); 
       break; 
    case 4: 
       anotherMethod(); 
       break; 
    
    0 讨论(0)
  • 2021-02-14 06:49

    Below is the best you can do

    case 1:
    case 2:
    case 3:
         aMethod();
         break;
     case 4:
         anotherMethod();
         break;
    
    0 讨论(0)
提交回复
热议问题