4 ms·
I'm with Mozilla. If I have a function with multiple conditions that cause me to return error / false / nil, I'd rather not have to nest them all in a series o
by xsmasher 17y ago
I'm with Mozilla.
If I have a function with multiple conditions that cause me to return error / false / nil, I'd rather not have to nest them all in a series of if/then/else statements nor combine them into a single more-complicated if condition. I'd rather write them each as separate if-and-returns, followed by the real meat of the function.
function updatePlayers{
if (charList is empty)
return false;
if (play is paused)
return false;
if (char is frozen)
return false;
//do stuff here
return true;
}
I think this better spells out the "error" conditions.
- philwelch 17y agoYou'd be right, of course, but the original article concedes this point. He's talking about situations like if (a < b) return a return b vs. if (a < b) return a else return b vs return ( (a < b) ? a : b)
- neilc 17y agoWhat is the distinction between those two situations? (i.e. those in which the article "concedes the point"?)
- nkurz 17y agoPresuming this is a genuine question: the difference is whether one goes on to do more work after the 'guard' return, or whether one is just choosing which value to return. I think the style guide is being silly, and there is no simple rule that says "always use an else" or "never use an else". I'd see "Avoid unnecessary indentation" as a better rule.
- philwelch 17y agoOne's an early return due to error, one's a conditional return value.
- natrius 17y agoGuard clauses are a particular case of if statements. I agree with omitting elses when using guard clauses. A blanket rule that eliminates elses after returns doesn't make any sense.
- njharman 17y agoBlanket rules don't make sense.
- wlievens 17y agoError is the wrong term, because you don't return after an error condition, you raise an exception. Perhaps stop condition is more appropriate?