...a little differently, like:
//first
while (condition())
{
x();
y();
}
x();
I know you were trying to avoid the duplication, so this isn't the target solution you were looking for, but this way is a bit cleaner and more obvious about what the code is meant to do.
Because, the whole point of the code appears to make sure that x() gets executed one last time after the loop. It seems somewhat more awkward to me to run the first iteration of x() before the loop begins than to run the extra execution after the loop, as a closing functionality.
I've seen people do the same thing with a counter loop, like:
i=0;
x();
for (i=1; i<end; i++)
{
y();
x();
}
It drives me nuts because using x() implies a partial first iteration of the loop and requires the use of the zero counter. Of course, your example doesn't use a counter, but it reads the same way, whereas putting the x() after the loop implies a followup execution of x() after everything else is done which is, as I said earlier, what the code appears to want to do.
Besides, in your example, I think the duplication is probably easier to understand (for whoever has to maintain the code later) than using the conditional exit. Forcing the condition check before the execution of y() makes it look like there is a dependency between the condition (whatever it is) and y(), when the only reason the condition check is there is to get that one extra execution of x(). Better to show that x() needs one more trip through when condition is met and loop is over than to suggest an inherent dependency that's not quite there.
Of course, the situation itself is awkward, having to use x() the way it's being used. For me, code like that would be begging to be rewritten or at least reviewed.
|