Hoist Loop 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-loop-from-if
Section titled “Sourcery refactoring id: hoist-loop-from-if”Description:
Section titled “Description:”Moves loops that occur in all cases of an if statement outside of the
conditional
Before:
Section titled “Before:”def sing_song(self): if style == 1: while thing_true(): do_x() elif style == 2: while thing_true(): do_y() elif style == 3: while thing_true(): do_z()After:
Section titled “After:”def sing_song(self): while thing_true(): if style == 1: do_x() elif style == 2: do_y() elif style == 3: do_z()Explanation:
Section titled “Explanation:”Where the same for or while loop is defined in all branches of a
conditional, the code can be considerably shortened and clarified by hoisting.
By moving the loop outside, duplication is removed and the code becomes much
clearer.