❔ Return in the middle of a method
Is it ok?
I think that it improves readability and performance, but a professor I know argues that it makes it harder to determine the state of a program and is therefore bad practice.
7 Replies
There is literally nothing wrong with this.
Returning in the middle of a method can make your method much more readable.
It's definitely much harder to read if this is not done when it is possible, since that would probably include having a pre-declared return variable which is being assigned at potentially multiple places, and then you have to piece together which parts of logic are exclusive depending on whether it is already set or not
So I definitely agree that early returns make your code much more readable
$itdepends
If it's actually in the middle of the method, and you cant easily avoid it, I'd probably add a comment why that specific state in that moment of your function means a complete abort of the function
Early returning can be more readable and more make sense like in cases such as nested loops
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.