Using a function’s return value as an if condition, good practice

coding-standardsconditionsconventionsprogramming practices

Do you think it is a good practice to use function return values as if conditions? I'm coding in PHP atm but it holds for many other languages.

if(isTheConditionMet($maybeSomeParams))
{
}

or

$res = isTheConditionMet($maybeSomeParams);
if($res)
{
}

I can't think of a situation where the first one creates a problem, can it?

EDIT: Assume return value is not going to be used after condition is evaluated.

Best Answer

In the code you posted, there's no reason to store the function result in a variable before using it. (Unless perhaps the name of the variable is sufficiently meaningful that it makes the code clearer to the reader.)

On the other hand, if you need to refer to the value more than once, you should probably store it in a variable rather than calling the function multiple times, which could be inefficient and/or wrong:

$res = isTheConditionMet($maybeSomeParams);
if ($res)
{
    echo "res = $res\n";
    // do stuff
}
Related Topic