Skip to content

Merge Repeated Ifs

Sourcery refactoring id: merge-repeated-ifs

Description:

Merges together the interior contents of if statements with identical conditions

Before:

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

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

After:

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

Explanation:

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.