Which is a better practice, generally speaking, and why? Under what circumstances would you change your mind?
function foo1(int x) {
int result;
if (x > 5) {
result = 2;
} else {
result = 7;
}
return result;
}
OR
function foo2(int x) {
if (x > 5) {
return 2;
} else {
return 7;
}
}
I prefer the second form where you just return immediately. The only considerations I’m aware of are as follows.
Benefits:
Risks:
I don’t worry about the risk much because that risk kind of exists anyway if you inadvertently nest the clean-up code inside a conditional block of some sort as you try to manage the various paths of execution retaining the return value until the end. I think the best bet is to keep the code simpler and easier to follow to avoid that kind of risk. I think that risk is also significantly helped by the coding structures available in modern languages such as “Using” and “Try/Finally”. I try to always use those for clean-up tasks now instead of simply putting the code at the end of the block.
I do make an exception, however, when other code wants to access the pending return value as a variable anyway (to add it to a cache for example, so that the result can be returned more quickly next time).