Two things I think about (obviously it's very context dependent):
- Quick returns go inside the condition to save a level of nesting in the function; try to minimize level of nesting of the main function body
- I try to return a value at the end of a function that will do the least harm if I somehow fall through (because maybe I've messed up the condition or something), for example:
def launch_nukes():
if you_are_sure():
launch()
abort()
It's not always obvious how best to structure a function to meet the second criteria, but in general I try to think defensively (how to minimize chances of bad bugs both now and when I come back in 6 months).
Comments
Two things I think about (obviously it's very context dependent):
- Quick returns go inside the condition to save a level of nesting in the function; try to minimize level of nesting of the main function body
- I try to return a value at the end of a function that will do the least harm if I somehow fall through (because maybe I've messed up the condition or something), for example:
It's not always obvious how best to structure a function to meet the second criteria, but in general I try to think defensively (how to minimize chances of bad bugs both now and when I come back in 6 months).