Possible Duplicate:
Should a function have only one return statement?
While reading the section on refactoring in Code Complete by Steve McConnell, I noticed a suggestion that ran contrary to what I personally believed. McConnell suggests that during a nested if-else-then block you should return immediately after calculating the answer. Prior to this, I designed my code to assign the result to a return variable and at the end of the routine return the variable. The following are two examples using both methods.
My Style:
public int fibonacciSeq( int n ) {
int result = 0;
if( n == 1 || n == 2 ) {
result = 1;
} else if( n > 2 ) {
result = fibonacciSeq( n - 1 ) + fibonacciSeq( n - 2 );
} else {
result = 0;
}
return result;
}
McConnell’s Style:
public int fibonacciSeq( int n ) {
if( n == 1 || n == 2 ) {
return 1;
} else if( n > 2 ) {
return fibonacciSeq( n - 1 ) + fibonacciSeq( n - 2);
}
return 0;
}
For the purpose of showing the two differences, I ignored the performance liability that this algorithm holds (both have running complexity of O(n^2)). Which of those is actually easier to read, and in a far more complex situation, would this still have the same answer?
--Edit-- Also requested is why is the answer the case?