Recently I wrote something like this:
public void doSomething(boolean b1, boolean b2){
while(true){
if(b1){
doThis();
}
if(b2){
doThat();
}
}
}
But I really don’t like this solution, because in every iteration you will have to check the 2 booleans. So as possible solution I could imagine to write 4 while loops with the ifs before each loop, but for obvious reasons this sucks in maintainability. Do you have any suggestions to make this piece of code nice and effective?
I agree that this is premature optimization, but here’s another construct you might be able to use if your language has guarantees on short-circuit evaluation. Since java does not allow you to cast
voidreturn types toboolean, you would need to modifydoThis()anddoThat()to returnboolean.The
(x && foo())will only execute the function if the value ofxis true, otherwise short-circuit evaluation will kick in.You would have to be extremely careful that your compiler does not just optimize away this entire expression since no values are actually assigned.
A real, possible optimization that will avoid both comparisons in all cases is to use a switch statement in the inner loop.