user2956272
user2956272

Reputation:

While loop - how to remove code duplication

It's not the first time I find myself in the following situation:

bool a = some_very_long_computation;
bool b = another_very_long_computation;
while (a && b) {
  ...
  a = some_very_long_computation;
  b = another_very_long_computation;
}

I don't want to compute everything in while condition, since computations are long and I want to give them appropriate names. I don't want to create helper functions, because computation uses many local variables, and passing them all will make the code much less readable (and it will be some_huge_call).

It's unknown whether loop body will be executed at least once.

What is a good pattern in such situation? Currently I face it in C++, but I've encountered this in other languages as well. I can solve it by using additional variable isFirstPass, but it looks ugly (and, I guess, will cause some warnings):

bool a, b;
bool isFirstPass = true;
do {
  if (!isFirstPass) {
    ...
  } else {
    isFirstPass = false;
  }
  a = some_very_long_computation;
  b = another_very_long_computation;
} while (a && b);

Upvotes: 0

Views: 363

Answers (1)

melpomene
melpomene

Reputation: 85867

The direct simplification of your code is:

while (
  some_very_long_computation &&
  another_very_long_computation
) {
  ...
}

If you want to keep the variables a and b:

bool a, b;
while (
  (a = some_very_long_computation) &&
  (b = another_very_long_computation)
) {
  ...
}

If you don't want to put the conditions into the while condition:

while (true) {
  bool a = some_very_long_computation;
  bool b = another_very_long_computation;
  if (!(a && b)) {
    break;
  }
  ...
}

You could also create helper lambdas (which have access to local variables):

auto fa = [&]() { return some_very_long_computation; };
auto fb = [&]() { return another_very_long_computation; };
while (fa() && fb()) {
  ...
}

Upvotes: 4

Related Questions