Skip to content

Lift Duplicated Conditional

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: lift-duplicated-conditional

Section titled “Sourcery refactoring id: lift-duplicated-conditional”

Lift repeated conditional into its own if statement

if isinstance(hat, Sombrero) and hat.colour == "green":
wear(hat)
elif isinstance(hat, Sombrero) and hat.colour == "red":
destroy(hat)
if isinstance(hat, Sombrero):
if hat.colour == "green":
wear(hat)
elif hat.colour == "red":
destroy(hat)

Duplicating conditions in an if statement makes things more difficult to read, and carries with it all the usual problems of code duplication. While normally we try to avoid adding nesting to the code, in this case it makes sense to lift the duplicated conditional into its own if statement.

It is now clearer at a glance that the whole if..elif chain relates only to sombreros and not other types of hat.

See also: hoist-repeated-if-condition, the related refactoring for repeated if blocks.