3 ms·
I'm big fan of separating functions into validation and logic using early returns: function doSomeStuff(input) { if(someInvariantIsUnsatisfied(input))
by p1necone 4y ago
I'm big fan of separating functions into validation and logic using early returns:
function doSomeStuff(input) {
if(someInvariantIsUnsatisfied(input)) {
return Error;
}
if(someOtherInvariantIsUnsatisfied(input)) {
return Error;
}
//do stuff
return result;
}
- Jtsummers 4y agoThe term for that is a "guard". Swift took it literally and introduced guard statements which force you to terminate the containing scope (return, throw, continue, break) or call a function that is marked as never returning. If control flow can ~~enter~~ exit the body of the guard statement without hitting one of those, it's a compiler error. EDIT: Exit the body of the guard statement, not enter.
- latexr 4y ago> ~~enter~~ I get you’re going for the non-standard markdown strike through, but that looks confusing and calls attention to something you meant to remove. You can (well, could) remove the word when editing.
- koromak 4y agoI find this the absolute most readable way to write defensive code. Huge fan.