| ▲ | mrgaro 2 days ago | |||||||||||||||||||
I remember having this argument with my professor at the school, who insisted that a function should have only one "return" clause at the very end. Even as I tried, I could not get him to explain why this would be valuable and how does this produce better code, so I'm interested on hearing your take on this? | ||||||||||||||||||||
| ▲ | superxpro12 2 days ago | parent [-] | |||||||||||||||||||
It helps prevent bugs with state. The apple login bypass bug comes to mind. Basically, you have code in an "if" statement, and if you return early in that if statement, you might have code that you needed to run, but didnt. Forcing devs to only "return once" encourages the dev to think through any stateful code that may be left in an intermediate state. In practice, at my shop, we permit early returns for trivial things at the top of a function, otherwise only one return at the bottom. That seems to be the best of both worlds for this particular rule. | ||||||||||||||||||||
| ||||||||||||||||||||