Use a “guard” to simplify your code structure
Heavily nested code is one of my bigger pet peeves. I’ve found that the more nesting there is in a block of code, the more likely it is that it’ll be confusing to follow. Here’s an example:
def something(request): if condition_a and condition_b and condition_c: lots more and_even_more etc if something_else: etc etc etc etc etc of code here return True else: return False
The “return False” is pretty far-removed from the set of conditions that will cause it to execute. An easy way to restructure this code (while still having the exact same functionality) would be to use the set of conditions as a guard:
def something(request): if not (condition_a and condition_b and condition_c): return False lots more and_even_more etc if something_else: etc etc etc etc etc of code here return True
Preemptive comment: I’m fully aware that some people feel very strongly about only having “single return point” for a function. I disagree. I’d rather minimize the number of return statements from a function, but in this case I think it adds clarity.
I’m with you on this one, Tony. Breaking out of a function as early as you can not only makes it clear what the error conditions are, it also lets you read through the meat of the code without having to trace a bunch of scattered edge cases. It makes the separation between expected and exceptional much clearer.