Possible Duplicate:
Where did the notion of “one return only” come from?
Which is better? I see pros and cons for both, so I can't really decide on which one to stick to.
Wrap in if clause
function doIt() {
if (successfulCondition) {
whenEverythingGoesWell();
}
}
- Pro: Shows programmer's intention through indentation.
- Con: Indentation can get really deep if you need to short circuit many times. For example,
doThirdThing()
requires the success ofdoSecondThing()
, which in turn requires the success ofdoFirstThing()
. This happens a lot in web development where many web services are not reliable.
Premature return
function doIt() {
if (!successfulCondition) {
return;
}
whenEverythingGoesWell();
}
- Pro: Subversion checkins would be succinct. Sometimes, I see co-workers wrap super long functions in an if clause. The whole shebang gets checked in and makes reading Subversion diffs difficult.
- Con: Requires you to read the whole function to figure out the various run paths.
git diff --ignore-space-change
to produce nicer diffs for this kind of thing."Con: Requires you to read the whole function to figure out the various run paths."
-- I'd argue you still have to do this with theif
-clauses, if slightly differently.