Skip to content

Hoist Repeated If Condition

Sourcery refactoring id: hoist-repeated-if-condition

Description

Move a repeated condition to a parent if block.

Before

if x < 5 and y < 10:
    grid = range(10)
if x < 5 and y < 100:
    grid = range(100)

After

if x < 5:
    if y < 10:
        grid = range(10)
    if y < 100:
        grid = range(100)

Explanation

Don't repeat yourself! Although nested code is normally discouraged, in this case it is easier to see the relationships between conditions.

See also: lift-duplicated-conditional, the related refactoring for if..elif blocks.

Back to top