by bwh2 · 14y ago · 0 comments
// Original
function render() {
$return = null;
if($condition1) {
if($condition2) {
$return = 2;
} else {
$return = 1;
}
} elseif($condition3) {
$return = 3;
} else {
$return = 4;
}
return $return;
}
But I'd rather read: // Refactored
function render() {
if($condition1 && $condition2) return 2;
if($condition1) return 1;
if($condition3) return 3;
return = 4;
} function render() {
$return = null;
if($condition1 && $condition2) $return = 2;
elseif($condition1) $return = 1;
elseif($condition3) $return = 3;
else $return = 4;
return $return
} r = 0;
outer: {
foreach (x in a) {
foreach (y in b) {
if (condition(a, b)) {
r = 1;
break outer;
}
}
}
return r;
instead of foreach (x in a) {
foreach (y in b) {
if (condition(a, b)) {
return 1;
}
}
}
return 0;See http://anthonysteele.co.uk/the-single-exit-point-law and http://anthonysteele.co.uk/returning-to-multiple-exit-points
ETA: I'm amused by how easily the LISP philosophy applies here: any problem can be solved with enough lambdas.
Then your choices include a try...finally block, a "using" statement if you're in c#, or ... limiting yourself to only 1 return. Multiple returns don't fix the problems in all cases, just most of them.
I'm assuming that this is on a language that has automatic garbage collection. The 1-return rule came about in C, which does not and so has a lot more cases where manual clean-up is required.