A personal favorite programming technique is reversing if-statements to remove excessive indentation levels.
This technique revolves around breaking from a function, loop, or script early instead of nesting if-statements into other if-statements.
As a result of this technique, code flow becomes flatter and less indented.
Disclaimer: The code examples in this article are only valid for demonstration purposes. They would be too verbose for production, use too many return statements, and lack documentation.
Code example
Take this Python code, for example:
def has_edit_permission(user):
# Big indent starts here
if user.is_logged_in:
if user.is_admin:
return True
if user.is_moderator:
return True
# Big indent ends here
return False
Now, lets reverse the overarching if-statement from the previous example:
def has_edit_permission(user):
# We reverse the if-statement here
if not user.is_logged_in:
return False
# This used to be one level deeper:
if user.is_admin:
return True
# This used to be one level deeper:
if user.is_moderator:
return True
return False
And there you have it: by reversing the first if-statement, we've flattened the function by one level.
Note: You can also use this technique inside loops by calling continue
early.
Have fun experimenting with this technique in your codebases!