3 ms·
Regarding having tons of exit points, I find it actually adds no more cognitive load to use only a single return per function, compared to having multiple retur
by seventh-chord 7y ago
Regarding having tons of exit points, I find it actually adds no more cognitive load to use only a single return per function, compared to having multiple returns and keeping resource-freeing up-to-date for each.
Most of the challenge in writing code with a single return seems to come from the fact that I'm not used to doing it. Of course, sometimes it leads to heavily nested control flow, although I'm not sure yet whether or not I mind that. It does certainly simplify reasoning about control flow though, especially in large functions.
That all being said, I'd still rather just have defer.
- simias 7y agoWhat you say makes sense but I'd advise beginners reading this comment not to overdo it. I've seen new coders "cargo culting" this one-return-per-function rule and leading to code that was, in my opinion, unnecessarily complicated. For instance parameter validation is one instance where I think an early return is very much warranted. There you typically have no cleanup to do since it's effectively the prelude of the function. Regarding nested error handling, I prefer the "goto fail" pattern. Some people are opposed to the use of goto as a matter of principle but I think in this case it's fine. It's effectively the poor man's RAII when you don't have destructors.
- Gibbon1 7y agoNot unreasonable for functions to have guard returns, a 'happy' return. And a goto fail return. That's decent pattern when you have a function that handles modifying state.
- augustk 7y ago> For instance parameter validation is one instance where I think an early return is very much warranted. There you typically have no cleanup to do since it's effectively the prelude of the function. That's what the assert statement is for; checking pre- and postconditions.