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?
If I had to rewrite this code, I would probably write it without a helper function:
Notice that there is no
elsenecessary after anifblock that ends withcontinue. This puts all conditions on the same level of importance, including the outerif(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.