Skip to content

Merge Repeated Ifs

Documentation Index

Fetch the complete documentation index at: https://docs.sourcery.ai/llms.txt

Use this file to discover all available pages before exploring further.

Sourcery refactoring id: merge-repeated-ifs

Section titled “Sourcery refactoring id: merge-repeated-ifs”

Merges together the interior contents of if statements with identical conditions

if wardrobe.hats:
self.happiness += 1
else:
self.happiness -= 1
if wardrobe.hats:
self.stylishness += 1
else:
self.stylishness -= 1
if wardrobe.hats:
self.happiness += 1
self.stylishness += 1
else:
self.happiness -= 1
self.stylishness -= 1

Where subsequent if statements have identical conditions it is logically equivalent to merge them together. This shortens the code and makes it easier to read and understand.

Note that this can only be done if the statements inside the first if condition have no effect on the condition itself.