Skip to content

Latest commit

 

History

History
126 lines (74 loc) · 3.13 KB

File metadata and controls

126 lines (74 loc) · 3.13 KB

Code Smell 83 - Variables Reassignment

Code Smell 83 - Variables Reassignment

Variable reuse is something we see in big chunks of code.

TL;DR: Don't reuse variable names. You break readability and refactor chances and gain nothing but laziness.

Problems

  • Readability

  • Refactor chances

  • Missed Optimization

  • Mutability

  • Garbage Collection Missed Opportunities

Solutions

  1. Define, use and dispose variables.

  2. Keep your Definition, Usage and Destroy variables short.

Sample Code

Wrong

class Item:
  def taxesCharged(self):
    return 1;

lastPurchase = Item('Soda');
# Do something with the purchase

taxAmount = lastPurchase.taxesCharged();
# Lots of stuff related to the purchase
# You drink the soda

# I cannot extract method from below without passing
# useless lastPurchase as parameter

# a few hours later..
lastPurchase = Item('Whisky');
# You bought another drink

taxAmount += lastPurchase.taxesCharged();

Right

class Item:
  def taxesCharged(self):
    return 1;
  
def buySupper():
  supperPurchase = Item('Soda');
  # Do something with the purchase
 
  # Lots of stuff related to the purchase
  # You drink the soda
  return supperPurchase;

def buyDrinks():
  # You could extract method! 

  # a few hours later..
  drinksPurchase = Item('Whisky');
  # You bough another drink
  
  return drinksPurchase;

taxAmount = buySupper().taxesCharged() + buyDrinks().taxesCharged();

Detection

Many linters can warn us from reusing variables

Tags

  • Readability

Conclusion

Reusing variables is a non-contextual copy and paste hint.

Relations

Code Smell 03 - Functions Are Too Long

More Info

Credits

Photo by Robby McCullough on Unsplash

Twitter


Either way you look at it (DRY or laziness), the idea is the same: make your program flexible. When change comes (and it always does), you'll have a much easier time changing with it.

Chris Pine

Software Engineering Great Quotes


This article is part of the CodeSmell Series.

How to Find the Stinky Parts of your Code