Swap If Else Branches
Sourcery refactoring id:
else branches of conditionals
if location == OUTSIDE: pass else: take_off_hat()
if location != OUTSIDE: take_off_hat() else: pass
One pattern we sometimes see is a conditional where nothing happens in the main
body, and all of the action is in the
In this case we can make the code shorter and more concise by swapping the main
body and the
else around. We have to make sure to invert the conditional, then
the logic from the
else clause moves into the main body.
We then have an
else clause which does nothing, so we can remove it.
if location != OUTSIDE: take_off_hat()
This is easier to read, and the intent of the conditional is clearer. When reading the code I don't have to mentally invert it to understand it, since that has been done for me.
Sourcery will also make this change if the
else can be dropped since the body
if is a guard condition.