While loop - how to remove code duplication

时间:2019-01-18 18:55:22

标签: c++ duplicates 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);

1 个答案:

答案 0 :(得分:3)

您的代码的直接简化为:

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

如果要保留变量ab

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

如果您不想将条件置于while条件中,

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

您还可以创建辅助lambda(可以访问局部变量):

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