Hoist Similar Statements from If
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: hoist-similar-statement-from-if
Section titled “Sourcery refactoring id: hoist-similar-statement-from-if”Description:
Section titled “Description:”Hoist nested repeated code outside conditional statements
Before:
Section titled “Before:”if condition: args = {"some": "args"} with db: make_db_change(args)else: args = {"some": "args"} with db: make_other_db_change(args)After:
Section titled “After:”args = {"some": "args"}with db: if condition: make_db_change(args) else: make_other_db_change(args)Explanation:
Section titled “Explanation:”We should always be on the lookout for ways to remove duplicated code. An opportunity for code hoisting is a nice way of doing so.
Sometimes code is repeated on both branches of a conditional, and the difference
between the branches occurs within a nested structure like a with. In this
case we can refactor the conditional so that the condition is moved into the
nested structure, hoisting the rest of the code and resulting in something
simpler.