Reusing variables makes scopes and boundaries harder to follow
TL;DR: Don't read and write the same variable for different purposes
-
Readability
-
Hidden problems
-
Don't reuse variables
-
Extract Method to isolate scopes
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.
// 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);
// 'total' variable is reused
function printLineTotal() {
double lineTotal = item.getPrice() * item.getQuantity();
System.out.println("Line total: " + lineTotal);
}
function printAmountTotal() {
double ammountTotal = order.getTotal() - order.getDiscount();
System.out.println( "Amount due: " + ammountTotal);
}
[X] Automatic
Linters can use the parse tree to find variable definition and usages.
- Readability
Avoid reusing variable names. Use more specific and different names.
Code Smell 03 - Functions Are Too Long
Code Smell 154 - Too Many Variables
Refactoring 002 - Extract Method
Simplicity before generality, use before reuse.
Kevlin Henney
Software Engineering Great Quotes
This article is part of the CodeSmell Series.