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”Description:
Section titled “Description:”Lift repeated conditional into its own if statement
Before:
Section titled “Before:”if isinstance(hat, Sombrero) and hat.colour == "green": wear(hat)elif isinstance(hat, Sombrero) and hat.colour == "red": destroy(hat)After:
Section titled “After:”if isinstance(hat, Sombrero): if hat.colour == "green": wear(hat) elif hat.colour == "red": destroy(hat)Explanation:
Section titled “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.