Every day I always come across this dilemma – is it best practice to check for an undesired state at the start of a function and return straight away or, is it best practice to check for a desired condition and continue else return false.
I understand that there wont be a 1 fits all solution and that this is really a style issue but I am just interested in what other developers would typically do.
I always find my self being indecisive every time this situation comes up.
As an example (coded in php):
Check for the undesired condition first…
function myFunction($myVal)
{
if ($myVal != 'desiredVal') {
return false;
}
//Continue here with main function code
return true;
}
Or, check for the desired condition first…
function myFunction($myVal)
{
if ($myVal == 'desiredVal') {
//continue here with main function code
return true;
}
return false;
}
It’s largely a matter of style and both are correct. I find error checking at the top followed by the main method functionality to be cleaner and easier to follow.
The best advice would be to pick a style and be consistent with it.