Hacker News new | ask | show | jobs
by gregmac 2080 days ago
To me the right answer is the one that works and is most readable.

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.