Skip to content

Instantly share code, notes, and snippets.

@icarovirtual
Last active August 11, 2019 18:01
Show Gist options
  • Save icarovirtual/f7132288935849caeec712251a094e9e to your computer and use it in GitHub Desktop.
Save icarovirtual/f7132288935849caeec712251a094e9e to your computer and use it in GitHub Desktop.
guard clauses: longer example
def func_not_guarded(self, param):
if param == 'something':
self.counter += 1
if self.counter > 10:
self.reached_ten()
else:
if self.counter < 5:
self.has_not_reached_5()
else:
self.has_not_reached_5()
else:
self.counter -= 1
def func_guarded(self, param):
if param != 'something':
self.counter -= 1
# You can call return even if the function doesn't return anything
return
# Important path in a low indentation level
self.counter += 1
if self.counter > 10:
self.reached_ten()
return
# By returning early, you don't need `else` statements
if self.counter < 5:
self.has_not_reached_5()
return
self.has_not_reached_5()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment