|
|
|
|
|
by brownbat
2080 days ago
|
|
Another design philosophy is that there should be one and only one exit point to a function whenever possible. Maybe that's fallen out of favor, or not important to most folks. But even if it's just a "nice-to-have," it's still a tradeoff here. If every if block includes a return statement, you're basically writing a case switch or a series of elifs anyway. The readability of those structures is highly dependent on the language and how it expects serial conditionals to be most efficiently written. |
|
Personally, I find there are other factors that are far more important than early vs single return, such as nesting, doing too many things, unit tests, matching style of the codebase, and just being too long. If your method fits on a screen and only has one or two levels of nesting, it's usually easy to comprehend no matter what. If anything, I usually find "one return" to make things longer, as it requires additional variable declarations, and sometimes is downright awkard (eg: returning from a switch statement).
You can rewrite the entire example using a single return with conditional (ternary) operators, but how does that affect the readability? It probably depends more on if that's common in the codebase, and how the developer uses spaces, brackets and newlines then anything else.
Unit tests also go a long way here. They prove each branch of the logic works and ensure it stays working if someone decides to change the style in the future. They also force the code to be written in a way that's testable which (generally) means it'll naturally be narrow in scope, loosely coupled and short. I'll take ugly but unit tested over "meets project style guide" code any day of the week.