r/programminghorror • u/Nomergraw • Jun 09 '26
What a simple constructor
Our former IT director (35+ years of experience) wrote this and didn't see what was wrong here.
268
Upvotes
r/programminghorror • u/Nomergraw • Jun 09 '26
Our former IT director (35+ years of experience) wrote this and didn't see what was wrong here.
View all comments
Show parent comment
1
u/conundorum Jul 23 '26 edited Jul 23 '26
Fair point, I missed that; everything after the early return was supposed to still use single-return, but I forgot. Editing to fix it.
But yeah, the idea is that using early
returnstatements properly can make code cleaner, without skipping over cleanup code and creating leaks. (Despite the slight flub here accidentally doing literally exactly that, oops. 😅 )It does get a bit messy sometimes, but that's why it works best when combined with single-return. Ultimately, it's best to treat early-return as just applying the single-return pattern on the task level, instead of on the function level; you can actually treat each early-return conditional as a single-return block to get the benefits of both. (With cleanup inside the conditional or at the end of the function, as appropriate. Early return block can handle its own cleanup if necessary, and/or jump to main cleanup block if necessary, for sufficiently messy functions. ...I hope you never actually have to do this, though.)
Ultimately, the early return pattern isn't as much about having multiple
returns (despite the name), as it is about isolating chunks that can force a return AND don't need to be part of the main cleanup. (Such as input validation or file-is-open verification.) It breaks the function body down from one large section with a single return statement, to a chain of smaller sections (that can each have their own single return statement, or be broken down recursively), followed by a larger "main" section (that still uses single-return for cleanup). Ideally, you can make each link its own thing, such as when it's just a simple check; if a task is more complex, it can still have its own cleanup blocks if needed (and helps to distinguish between "prep" cleanup and "main task" cleanup).Edit: Did it again, the validator nonsense block's cleanup was a bit messed up. Jumped to full environment cleanup on
VALIDATOR_ENVIRON_CHOKEand returned early for any other errors, but was supposed to return early onVALIDATOR_PREP_FAILand jump to full environment cleanup for any other errors. And added the main return statement, I kinda forgot that it was actually meant to return something at some point. ...Trying to come up with halfway believable "bad code made less awful by refactoring" is hard. -_-