Suppose that I'm using C++. Now I have the following code:
int flag;
// ...
while (!TimeToExitLoop()) {
Func();
}
The while
loop will be executed a huge number of times, and Func
is a time-critical function like this:
void Func() {
// some big stuff ...
if (flag > 1) {
// logic 1 ...
}
else {
// logic 2 ...
}
}
Also, the value of flag
won't be change within the while
loop. Therefore, it is better to move the conditional if
statement out of the while
loop, and define two separate functions for the two conditions like this:
int flag;
// ...
if (flag > 1) {
while (!TimeToExitLoop()) {
Func_FlagBiggerThanOne();
}
}
else {
while (!TimeToExitLoop()) {
Func_FlagNoBiggerThanOne();
}
}
However, that will result in the repetition of the "big stuff" in Func
by Func_FlagBiggerThanOne
and Func_FlagNoBiggerThanOne
:
void Func_FlagBiggerThanOne() {
// big stuff ...
// logic 1 ...
}
void Func_FlagNoBiggerThanOne() {
// big stuff ...
// logic 2 ...
}
which will violate the Don't-Repeat-Yourself principle. We can not put that "big stuff" in some function because invoking that function will be more time consuming than the original if
statement. One of the solutions is to define a macro for that big stuff, but what if "logic 1" and "logic 2" will use the variables defined in "big stuff"? Though macro still works, that may result in ugly code, the programme's reader might think, "where the heck are those variables defined?"