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

有帮助吗?

解决方案

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.

其他提示

If cnt is used only to control how many times doSomething(), etc., are called, you should consider passing it into the method and looping inside the method. Normally I would say don't worry about performance, but if you're actually talking about 10^9 iterations, you should avoid repeating the switch.

Option 2 is more straightforward as you are putting the emphasis on the switch-statement and having to work through a case in every iteration might consume more time.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top