Page 1 of 1
When to return
Posted: Wed May 18, 2011 1:20 am
by social_experiment
Which of the following functions contains the better use of 'return'? Both do the same thing but is there a preferred way (coding standard related) on how to use return.
Code: Select all
function whenToReturn($value) {
if ($value == '') {
$value = FALSE;
}
else {
$value = trim($value);
}
return $value;
}
#---
function whenToReturn($value) {
if ($value == '') {
$value = FALSE;
return $value;
}
else {
$value = trim($value);
return $value;
}
}
Re: When to return
Posted: Wed May 18, 2011 6:38 am
by Apollo
Feels like unnecessary clutter / redundancy. How about:
Code: Select all
function whenToReturn( $value )
{
if ($value=='')
{
return false;
}
else
{
return trim($value);
}
}
Although in that case I'd prefer:
Code: Select all
function whenToReturn( $value )
{
if ($value=='')
{
return false;
}
return trim($value);
}
Or even:
Code: Select all
function whenToReturn( $value )
{
return ($value=='') ? false : trim($value);
}
Re: When to return
Posted: Wed May 18, 2011 10:50 am
by Jonah Bron
I generally like to limit my functions to one return, but I do make exceptions from time to time. But if you keep your functions small, it shouldn't really matter either way.
Re: When to return
Posted: Thu May 19, 2011 7:03 am
by social_experiment
@Apollo : I didn't realise that you could just return false instead of assigning false to a variable (or maybe i did but i just didn't think about it at the time). Thanks for tip

Re: When to return
Posted: Thu May 19, 2011 2:14 pm
by koen.h
I agree with Johah Bron: one return mostly and occasionally more than one. I do whatever is most likely to have me understand the code fastest upon having to reexamine it. That does not mean going from one line to the next but grasping the big part, which most often lead me to the part I need to check. If I would need to debug the return value of your first example I probably would have to read more code before I came to the part I think could be the problem (eg need to find 2 returns within 2 possibilities).
Re: When to return
Posted: Mon Jun 13, 2011 1:50 am
by Benjamin
Returns can be used as code flow control when your halfway between using a try catch block or utilizing decomposition to simplify/organize a chunk of code for example.
I prefer to use multiple returns in some cases to "jump" back out of a method as quickly and efficiently as possible. I'm sure that the performance increase is less noticeable than watching a hummingbird flap her wings but I do it anyway and it really doesn't create any bloat.
You can actually return out of an include file also, which I think maybe many programmers don't realize. In other words if you include a file, and in that file at some point you decide you don't want to execute the code in it any further, you can simply return.