I've recently come across this code:
do {
if ( ! checkSomething() )
break;
// some code
if ( ! checkSomeOtherThing() )
break;
// some other code
} while(false);
// some final code
The programmer that wrote it, wrote a comment along the lines of "cleaner control flow"
.
In my opinion, the original code could look better if its refactored into something else. But is there any truth in this statement ? Is this construct any good ?
If you don't mind loops containing several break
statements, then the only problem here is that C (for obvious reasons) doesn't let you break out of a bare block, hence the "non-loop" which some unsuspecting future maintainer could mistake for a real loop.
The considerations, I think, are:
break
points, what's so bad about two if
statements?if
statements could get unpleasant, and this saves that, but then again is the function doing too much? And even if not, would it be better just to use goto
and avoid the weirdness of a loop that doesn't loop?Since you tag this language-agnostic, I used to use a macroised assembly language, with a block
... endblock
that you could break out of. This lead to reasonably nice code for checking necessary conditions, such as:
block
breakif str1 == null
breakif str2 == null
get some combined property of str1 and str2
breakif some other condition that stops us getting on with it
get on with it
endblock
Actually, it wasn't breakif str1 == null
, it was breakifeq.p str1, null
, or something like that, but I forget exactly what.