Lift Duplicated Conditional¶
Sourcery refactoring id: lift-duplicated-conditional¶
Description:¶
Lift repeated conditional into its own if statement
Before:¶
if isinstance(hat, Sombrero) and hat.colour == "green":
wear(hat)
elif isinstance(hat, Sombrero) and hat.colour == "red":
destroy(hat)
After:¶
if isinstance(hat, Sombrero):
if hat.colour == "green":
wear(hat)
elif hat.colour == "red":
destroy(hat)
Explanation:¶
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.