I have often been told that I should not use multiple return points, instead I should just use one:
take for example this function;
function data($item){
switch($item){
case 'one':
return 1;
case 'two':
return 2;
case 'three':
return 3;
case 'different_type':
return 'Something Different';
default:
return false;
}
}
Apparently a better way of writing this would be;
function data($item){
$value = false;
switch($item){
case 'one':
$value = 1;
break;
case 'two':
$value = 2;
break;
case 'three':
$value = 3;
break;
case 'different_type':
$value = 'Something Different';
break;
default:
$value = false;
}
return $value;
}
Is there any reason that is not a matter of preference for one over the other?
I imagine that the second one gives some IDE’s a better chance at type hinting the return value? but are there performance issues here as well?
Sometimes but that depends on concrete code.
No, that is normally not the case.
Early returns can shortcut longer paths in the code so can have a benefit.
A good coding guideline does normally not govern this strictly nowadays, in earlier times with languages not that flexible it might have made sense to keep a strict approach (last line of a function must be the single return command).
Nowadays it is known that it is more important to reduce Cyclomatic Complexity which is often the case with returning early. However, take this with a grain of salt, it’s not that if you return early ever, that this is automatically the case.
As you’re speaking about code, the first example should be in my eyes:
But this would also run counter your example.