Re:Avoid Else, Return Early (2013)
by RobertRoberts on Monday March 26, 2018 @01:12PM
(#16680531)
Can't that be taught as well? (both rules, and exceptions to rules?)
Re:Avoid Else, Return Early (2013)
by macspoofing on Monday March 26, 2018 @01:24PM
(#16680667)
Sure.
But as a novice youd should adhere to rules. As you gain experience you learn when to break them.
Re:Avoid Else, Return Early (2013)
by RobertRoberts on Monday March 26, 2018 @03:30PM
(#16681706)
I think you read my comment backwards.
I think the "rule" should be "exit early", and the exception "multi-indent exit later".
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.