This is really not elegant:
$retry = 0;
do {
try {
$this->foo();
$retry = 0;
}
catch (FooException $e) {
$retry++;
}
} while ((!$retry && $fooCondition()) || ($retry === 1))
This is to say, do something, if succeeded then reset retries to 0, if it failed increase the number of retries. If this is not a retry, check the normal loop condition. But even if the normal loop condition fails, if this is a retry, loop.
Is there really not a more elegant construct to express this?
3
Answers
I changed the counter to a boolean and added one more variable and it became a lot more readable:
The original version expressed this by saying "if the try section executed successful then retries is zero and then $fooCondition() decides whether to loop. Otherwise retries is not zero and then we need to loop if this is the first retry." But there is no need for such a complex expression, we can just simply set the loop condition itself in the try and the catch sections. A good IDE -- like PhpStorm -- will highlight the places where
$needs_more
is set, making it rather easy to see and comprehend.Simplify.
Try this? Look a bit more elegant.