Skip to content

Hoist Similar Statements from If

Sourcery refactoring id: hoist-similar-statement-from-if

Description:

Hoist nested repeated code outside conditional statements

Before:

if condition:
    args = {"some": "args"}
    with db:
        make_db_change(args)
else:
    args = {"some": "args"}
    with db:
        make_other_db_change(args)

After:

args = {"some": "args"}
with db:
    if condition:
        make_db_change(args)
    else:
        make_other_db_change(args)

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.

Was this page helpful?