Last active
July 13, 2020 05:49
-
-
Save psyonara/3cf53bc7f16e71030b5ad190214002d7 to your computer and use it in GitHub Desktop.
Shows how to refactor Python code using the early exit pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Code for blog article: | |
# https://www.helmut.dev/early-exit.html | |
# Original code | |
if post_data: | |
thing = post_data.get("thing") | |
if thing is not None: | |
setting = get_user_setting(user, thing) | |
if setting is not None: | |
permission = get_user_permission(user) | |
if permission is True: | |
if user.is_superuser: | |
return DataPoint.objects.all() | |
elif user.is_staff: | |
return DataPoint.objects.filter(user=user) | |
else: | |
return DataPoint.objects.filter(user=user, thing=thing) | |
else: | |
return "Permission denied" | |
else: | |
return "Setting not found" | |
else: | |
return "Thing not specified" | |
else: | |
return "No data posted" | |
# Refactored code | |
if not post_data: | |
return "No data posted" | |
thing = post_data.get("thing") | |
if thing is None: | |
return "Thing not specified" | |
setting = get_user_settig(user, thing) | |
if setting is None: | |
return "Setting not found" | |
permission = get_user_permission(user) | |
if permission is False: | |
return "Permission denied" | |
if user.is_superuser: | |
return DataPoint.objects.all() | |
if user.is_staff: | |
return DataPoint.objects.filter(user=user) | |
return DataPoint.objects.filter(user=user, thing=thing) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment