Code Smell 107 - Variables Reuse

mcsee

Maxi Contieri

Posted on December 1, 2021

Code Smell 107 - Variables Reuse

Code Smell 107 - Variables Reuse

Reusing variables makes scopes and boundaries harder to follow

TL;DR: Don't read and write the same variable for different purposes

Problems

  • Readability

  • Hidden problems

Solutions

  1. Don't reuse variables

  2. Extract Method to isolate scopes

Context

When programming a script it is common to reuse variables.

This leads to confusion and makes debugging harder.

We should narrow the scope as much as possible.

Sample Code

Wrong

// print line total
double total = item.getPrice() * item.getQuantity();
System.out.println("Line total: " + total );

// print amount total 
total = order.getTotal() - order.getDiscount();
System.out.println( "Amount due: " + total );

// variable is reused
Enter fullscreen mode Exit fullscreen mode

Right

function printLineTotal() {
  double total = item.getPrice() * item.getQuantity();
  System.out.println("Line total: " + total );
}

function printAmountTotal() {
  double total = order.getTotal() - order.getDiscount();
  System.out.println( "Amount due: " + total );
}
Enter fullscreen mode Exit fullscreen mode

Detection

[X] Automatic

Linters can use the parse tree to find variable definition and usages.

Tags

  • Readability

Conclusion

Avoid reusing variable names. Use more specific and different names.

Relations

More Info

Credits

Photo by Sigmund on Unsplash


Simplicity before generality, use before reuse.

Kevlin Henney


This article is part of the CodeSmell Series.

💖 💪 🙅 🚩
mcsee
Maxi Contieri

Posted on December 1, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related