5 ms·
> 11. Never use early exits. As a general piece of advice, this is flat out wrong. Or, to put it more correctly, this is only valid advice when using certain l
by ghc 14y ago
> 11. Never use early exits.
As a general piece of advice, this is flat out wrong. Or, to put it more correctly, this is only valid advice when using certain languages and only under certain conditions. Just because it is sound advice in languages with C/C++ derived syntax doesn't mean it should be presented as good advice in general.
- albertzeyer 14y agoWhy do you think it is bad for C? Take for example the Linux kernel where you find early exits basically everywhere. (See also my other response here: http://news.ycombinator.com/item?id=4626763 http://news.ycombinator.com/item?id=4626763) Even less bad in C++ where destructors can automatically handle any cleanup (exactly that is also common practice in C++; making the cleanup implicit). Similarly in many other more high level languages with GC and/or automatic refcounting or so. In rare cases, it might be more complicated, though. But you seem to have some languages in mind where it really doesn't matter? What languages?
- glassx 14y agoWell, most early returns are avoided mostly because it makes it harder to understand the code. But when you use guard clauses, like on your Linux Kernel example, you actually improve the code, because you reduce cyclomatic complexity (everything is now a linear path: a -> b -> c), you can reduce nesting, you can avoid unnecessary mutable state... so it's a win. The problem with early returns is when you use them in non-obvious places. I believe that the majority of programmers agrees that using early returns for guard clauses is an okay exception.
- dllthomas 14y agoYes, I think really "avoid early returns" is an overextended special case of "avoid the nonobvious".
- glassx 14y agoExactly. Also, for example, when you have lots of "if" clauses, those languages force us to use mutable state (and a variable initialized as null) just to avoid early exits. But we can avoid both by treating the "if" as an expression, as in Ruby, Lisp, etc, or with the ternary conditional operator... Plus, IMO, there are some situations where early exits are a good idea even in languages derived from C, such as with guard clauses/preconditions. There's a nice discussion about that here with some points I made: http://c2.com/cgi/wiki?SingleFunctionExitPoint http://c2.com/cgi/wiki?SingleFunctionExitPoint (EDIT: I edited a lot but still couldn't make it clear that I agree with you, but I still ended up making points about completely different things, sorry about that, my english skills are lacking sometimes)
- SimHacker 14y agoI understand why not to use early exits. But what's wrong with early returns?
- nwmcsween 14y agoHuh? You _want_ early exits in c code how else will the compiler optimize?