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
Don't reuse variables
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
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 );
}
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

Code Smell 03 - Functions Are Too Long
Maxi Contieri βββ γ» Oct 22 '20 γ» 1 min read
More Info

Refactoring 002 - Extract Method
Maxi Contieri βββ γ» Nov 25 '21 γ» 2 min read
Credits
Simplicity before generality, use before reuse.
Kevlin Henney

Software Engineering Great Quotes
Maxi Contieri βββ γ» Dec 28 '20 γ» 13 min read
This article is part of the CodeSmell Series.
Top comments (1)
Great reminder I did something similar recently, reusing variables i mean.