Refactoring loop iteration logic into helper function with continue statements

141 Views Asked by At

I have a function that looks (simplified) like the following:

void function() {
  // compute n
  int n = ....
  for (int i = 0; i < n; ++i) {
    if (certain condition is met) {
      if (another condition is met) {
        // do some stuff here
        continue;
      } else if {
        // do some other stuff here
        continue;
      } else {
        // do some other stuff here
      }

      // do stuff here
    }
  }
}

I would like to refactor everything in the loop to a helper function, so something like

// This function is called within a loop and returns true if current iteration needs to be continued.
bool helper() {
  if (another condition is met) {
    // do some stuff here
    return true;
  } else if {
    // do some other stuff here
    return true;
  } else {
    // do some other stuff here
  }
  return false;
}
void function() {
  // compute n
  int n = ....
  for (int i = 0; i < n; ++i) {
    if (certain condition is met) {
       if (helper()) {
         continue;
       } 
       // do stuff here
    }
  }
}

I was wondering if there's an easier way to write this without having to have the helper() return a bool that tells the function whether the current loop iteration needs to be continued or not?

1

There are 1 best solutions below

0
j6t On

If I had to rewrite this code, I would probably write it without a helper function:

void function()
{
  // compute n
  int n = ....
  for (int i = 0; i < n; ++i)
  {
    if (certain condition is _not_ met)
      continue;

    if (another condition is met)
    {
      // do some stuff here
      continue;
    }

    if (yet another condition)
    {
      // do some other stuff here
      continue;
    }

    // do some other stuff here

    // do stuff here
  }
}

Notice that there is no else necessary after an if block that ends with continue. This puts all conditions on the same level of importance, including the outer if (unless you forgot to show us some common part near the end of the loop that should run unconditionally).

You also see now that there are two sequences of "stuff" that are executed if no condition applies that were previously separate. This may indicate a flaw in the logic.