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 ?
I find this much easier to read, and it produces an identical result:
if ( checkSomething() )
{
// some code
if ( checkSomeOtherThing() )
{
// some other code
}
}
// some final code
I think do ... while is normally hard to follow, but using it for something other than a loop is misleading at best.
This is equivalent to a goto.
In such situations, it is better to use a goto than to use an ugly hack.
Changing it to use a goto makes it much more readable:
if (!checkSomething())
goto Done;
// some code
if (!checkSomeOtherThing())
goto Done;
// some other code
Done: //some final code
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With