4 ms·
Generally good advice, but w/r/t the first recommendation, I prefer to structure if/else clauses so that common case is handled first and the exceptional case i
by RyanMcGreal 14y ago
Generally good advice, but w/r/t the first recommendation, I prefer to structure if/else clauses so that common case is handled first and the exceptional case is handled last.
- kibwen 14y agoI like to do this as well, both for reasons of clarity and because I like to imagine that it saves my code from executing an often-wasted conditional (though I really have no idea if the order of branch condition evaluation is guaranteed in the face of compiler transformations, or if branch prediction and/or speculative execution make this point completely moot).
- dwc 14y agoAs shown in the article, that first recommendation leads directly to the next step(s). In the ideal case (which actually happens sometimes in the real world!), you end up with something like this: if (bad1) fail(); if (bad2) fail(); if (bad3) fail(); step1(); step2(); step3(); step4(); return SUCCESS; To me, this is a very nice way to structure things when you can. You get a checklist of things that might be wrong, and then comes the wonderfully naive straightforward implementation.
- davidhollander 14y agoStating failures first can also be considered analogous to input validation, preconditions, or declaring the domain for which the function is undefined. Some related discussion on here: http://c2.com/cgi/wiki?GuardClause http://c2.com/cgi/wiki?GuardClause