Search code examples
refactoringwhile-loopswitch-statementcode-readability

Switch statement into while loop or while loop into case blocks?


I'm refactoring some code I wrote and I have to decide if I wanna put a switch statement into a while loop or repeat the while loop into each case blocks. The two different ways are something like the following pseudocode:

Option 1)

while (cnt > 0) {
    switch (value) {
    case A:
        doSomething();
        break;
    case B:
        doSomethingElse();
        break;
    ...
    default:
        default();
        break;
    }
    cnt--;
}

Option 2)

switch (value) {
case A:
     while( cnt > 0){
        doSomething();
        cnt--;
      }
case B:
     while( cnt > 0){
        doSomethingElse();
        cnt--;
      }
...
default: 
     while( cnt > 0){
        default();
        cnt--;
      }
}

I think the first option follows better the DRY principle because I don't repeat every time the while and the cnt--. Although I like a bit better the second option because once it picks a case in the switch statement, it starts to loop in the while and it doesn't have to evaluate the switch condition anymore.

So, which of these two solutions would you pick and why?

NB: We can assume that the switch-condition (i.e. the variable "value" in the code below) doesn't change for the entire while loop, in other words: the operations doSomething(), doSomethingElse() etc. do not affect the switch statement.

NB2: In the real code I'm working on, the while loop can be very huge. "Cnt", for some test cases, can be of the order of 10^9


Solution

  • In most cases, a Loop-switch sequence is an antipattern you should avoid for the sake of clarity, and since you mention cnt can become quite huge also for the sake of performance.