Function Returns
(Programming)
There is and has for a long time been debate in the programming community about whether it’s Good, Right, or Holy to check out of a function early with a semaphore value (usually TRUE or FALSE). For example, if there’s a routine called set_name($name), and some idiot calls the routine without a name. Normally if someone called that routine with a name, you’d set some internal variable to the value of the passed name parameter. The routine would then exit at the end with a TRUE value. But in our case, the programmer omitted the name parameter. We detect this and set an error condition. We could pass out of our testing loop and eventually end up with the end, with a FALSE to return. Like this:
function set_name($name)
{
$errors = 0;
if (empty($name)) {
echo 'No name provided!';
$error++;
}
else {
$this->name = $name;
}
if ($error) {
return FALSE;
}
else {
return TRUE;
}
}
The eternal question is whether you should simply exit as soon as you detect the error (possibly with an error message), or pass through the rest of the function, waiting until the very end of the function, and return just like you would on success, except with a different (error) return value.
The answer is simple. Get the hell out of that function as fast as you can. That way, there are no added complications, no spending time trying to figure out how not to execute the rest of the function, etc. It’s just simpler, and simpler when you’re tracing through old code. On error, you don’t have to trace through code which is moot. The route out of the routine is more direct and less complicated. Like this:
function set_name($name)
{
if (empty($name)) {
echo 'No name provided!';
return FALSE;
}
$this->name = $name;
return TRUE;
}
Notice how much simpler that function became? I’ve reduced the number of lines by about half. And if I have to go back tracing the code, I don’t even have to read the rest of the code if there’s an error condition.
This is not a license to take every other shortcut in the book with your code, and thereby make it unreadable. I’ve seen lots of programmers do that, just because they can and they think it’s clever. Remember, readability and traceability are more important than code which will impress your co-workers.
Also, note that I’m not advocating for “gotos”. An early return is not a goto. Gotos are a whole different discussion.