lundi 17 octobre 2016

if statement - short circuit evaluation vs readability

Sometimes, if statement is rather complicated or long, so for the sake of readability it is better to extract complicated calls before the if.

e.g. this:

if (SomeComplicatedFunctionCall() || OtherComplicatedFunctionCall())
{
    // do stuff
}

into this

bool b1 = SomeComplicatedFunctionCall();
bool b2 = OtherComplicatedFunctionCall();

if (b1 || b2)
{
    //do stuff
}

(provided example is not that bad, it is just for ilustration... imagine more calls with multiple arguments etc.)

But witch this extraction I lost the short circuit evaluation (SCE).

1) Do I really lose SCE every time? Is compiler is some scenario allowed to "optimize it" and still provide SCE?

2) What is the best practice in such situation? Is it only possibility (when I want SCE) to have all I need directly inside if and "just format it to be as readable as possible" ?

Aucun commentaire:

Enregistrer un commentaire