Skip to content

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”

Hoist nested repeated code outside conditional statements

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

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.