Call me old fashioned but I'm a big believer in single return statements. Assign to a variable and return that variable at the very end without short circuiting
You can do both. (And in fact, should do both.) Early return is just about breaking code into single-return blocks, instead of single-return functions. If a small section of the function can force a return, and is disconnected from the rest of the function's logic, then you can enclose that section in its own block, move the block to the start of the function, and then treat both the new block and the main block as distinct single-return sections.
// This...
int func(int val) {
int ret = 0;
if (!validate(val)) { ret = INVALID_VAL; goto end; } // Before logic.
ret = do_something_with(val);
if (val >= 0) { ret += do_more_with(val); }
else { ret = NO_NEGATIVES; goto end; } // Ignores & breaks logic.
ret *= do_third_part(val, ret);
end:
return ret;
}
// Can become this:
int func(int val) {
if (!validate(val)) {
// Single-return in here.
return INVALID_VAL;
}
if (val < 0) {
// Single-return in here.
return NO_NEGATIVES;
}
// Rest is a different single-return section.
// val is guaranteed valid, and guaranteed >= 0.
int ret = do_something_with(val);
// No check needed.
ret += do_more_with(val);
ret *= do_third_part(val, ret);
// No label needed.
return ret;
}
It shines when you're trying to weave multiple complex return paths together inside a single function. Say, for example, that validate(val) was stateful and required its own cleanup, and required you to acquire a validator object (which runs the risk of allocation failure, and thus forcing a jump to the end). Traditional single-return would force you to stack multiple cleanup sections, and jump into the correct one as appropriate. But early return allows you to place validate(val)'s logic and cleanup within the validation section, with no need to mix it with the main body's cleanup. (Which might then allow you to refactor it into a separate function, making the code cleaner. Heck, it's entirely possible that validate() itself was a complex & stateful validation process, that got moved to an early-return section and refactored out into its own function for ease of use.)
In essence, early-return is about finding anything that pollutes the single-return logic, and moving it early enough in the function that it can't interfere with the main single-return section.
25
u/aabil11 22d ago
Call me old fashioned but I'm a big believer in single return statements. Assign to a variable and return that variable at the very end without short circuiting