Skip to content

Move Assign In Block

Sourcery refactoring id: move-assign-in-block

Description:

Moves assignment of variables closer to their usage within a block

Before:

cubes = []
function_unrelated_to_cubes()
if another_unrelated_condition():
    more_unrelated_logic()
for i in range(20):
    cubes.append(i**3)

After:

function_unrelated_to_cubes()
if another_unrelated_condition():
    more_unrelated_logic()
cubes = []
for i in range(20):
    cubes.append(i**3)

Explanation:

The scope of local variables should always be as tightly defined as possible and practicable.

This means that:

  • You don't have to keep the variable in your working memory through the parts of the function where it's not needed. This cuts down on the cognitive load of understanding your code.
  • If code is in coherent blocks where variables are declared and used together, it makes it easier to split functions apart, which can lead to shorter, easier to understand methods.
  • If variables are declared far from their usage, they can become stranded. If the code where they are used is later changed or removed unused variables can be left sitting around, complicating the code unnecessarily.