Skip to content

Move Assign

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.

Moves assignment of variables closer to their usage

def should_i_wear_this_hat(self, hat):
if not isinstance(hat, Hat):
return False
weather_outside = self.look_out_of_window()
is_stylish = isinstance(hat, StylishHat)
if weather_outside.is_raining:
print("Damn.")
return True
else:
print("Great.")
return is_stylish
def should_i_wear_this_hat(self, hat):
if not isinstance(hat, Hat):
return False
weather_outside = self.look_out_of_window()
if weather_outside.is_raining:
print("Damn.")
return True
else:
print("Great.")
is_stylish = isinstance(hat, StylishHat)
return is_stylish

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.