Hoist 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-statement-from-if
Section titled “Sourcery refactoring id: hoist-statement-from-if”Description:
Section titled “Description:”Moves statements that occur in all cases of an if statement outside of the
conditional
Before:
Section titled “Before:”if sold > DISCOUNT_AMOUNT: total = sold * DISCOUNT_PRICE label = f"Total: {total}"else: total = sold * PRICE label = f"Total: {total}"After:
Section titled “After:”if sold > DISCOUNT_AMOUNT: total = sold * DISCOUNT_PRICEelse: total = sold * PRICElabel = f"Total: {total}"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. This means that the code will always execute. The duplicate lines can be hoisted out of the conditional and replaced with a single line.
By taking the assignment to label outside of the conditional we have removed a
duplicate line of code, and made it clearer what the conditional is actually
controlling, which is the total.