4 ms·
I find it interesting how most of the comments about return early are based on experience. I had the same thing happen about 10 years in. I just got sick of th
by RobertRoberts 9y ago
I find it interesting how most of the comments about return early are based on experience.
I had the same thing happen about 10 years in. I just got sick of the extra coding and long indented blocks. And just switched over one day.
Why is this not taught from day one?
- macspoofing 9y agoThe problem is that for any rule you come up with there are cases where that rule is just too rigid and too inflexible. There are times where early return makes a ton of sense. Usually that's the case when you can derive the return value from a shallow interpretation of some input values (i.e. check preconditions) but still require more complex processing for other input values. In that case, return early, but constrain the rest of the method to one return point. On the flip-side, there are cases where an early return makes it incredibly hard to reason about the function. This usually occurs in dense, nested conditional logic. In those cases, I found sticking to rule that a return value should be initialized once and only once, and return from a single point, beneficial in even reasoning about the problem.
- RobertRoberts 9y agoCan't that be taught as well? (both rules, and exceptions to rules?)
- macspoofing 9y agoSure. But as a novice youd should adhere to rules. As you gain experience you learn when to break them.
- RobertRoberts 9y agoI think you read my comment backwards. I think the "rule" should be "exit early", and the exception "multi-indent exit later".
- Wildgoose 9y agoI sold my first program aged 15 and I'm 53 now. My experience is that the benefit of early return is to keep indentation to a minimum. To me, every time code indents it is a "context switch". Having said that, early return should be for error/ignore situations - there should only be one return for a result and that should be at the very end of the function.
- egypturnash 9y agoHabits based on what was fastest on slow machines where every cycle mattered and compilers weren’t as good at optimizing, I’d bet.
- Apatheticdino 9y agoI'd like to believe that this is a result of the concept of functions being first taught in the context of mathematics. Since there's no concept of flow control in mathematical functions, their entire purpose boils down to "Given parameters, do processing, return value".
- rukuu001 9y agoWe were taught "one entry, one exit". I now think of the early part of a function as a filter for bad params, invalid state & whatnot, and return as early as possible. Code just feels less complex that way.