6 ms·
In many situations you can fix this by adding a not to the if statement. eg, Before: if (a.works()) { // some code if (b.works()) { /
by proverbialbunny 7y ago
In many situations you can fix this by adding a not to the if statement. eg,
Before:
if (a.works()) {
// some code
if (b.works()) {
// more code
}
}
After:
if (!a.works()) {
// error handling code, if necessary
return;
}
// some code
if (!b.works()) {
// error handling code, if necessary
return;
}
// more code
- quietbritishjim 7y agoThis is called "early return" and the parent already mentioned it: > if you're gonna punt, early-return
- afiori 7y agohere there is some significant restructuring of the flow control, early returns could have just meant return statements in the middle of the function.
- quietbritishjim 7y agoI'm really quite sure they were referring to the type of code in your comment. Early return on error (as in, what you posted) vs single return with deeply nested if statements is an absolutely classic coding debate.
- afiori 7y agojust as a quick clarification, I am not the OP
- quietbritishjim 7y agoOops, I did indeed miss that. I suppose that shows that it was helpful to spell it out.
- giancarlostoro 7y agoI usually try to bail out of my code early on in Python so I have all my if bail condition statements before I bother trying to do any other logic. Actually I do this in all languages. Bail early and you wont have spaghetti code, plus you wont even allocate things to memory you're not even going to use, cause you're going to bail.