Split Temporary Variable is used when there is a temporary variable that is assigned to more than once. Here a temporary variable means a variable that is not a loop index or a collecting temporary variable.
Collecting Temporary Variable
A collecting temporary variable is exactly what it sounds like—a temporary variable that collects a value. Think of a sum or a product that is built in a loop or as the result of a LINQ query. In the following example we see a collecting temporary variable, and this is the type of temporary variable that would not be refactored by split temporary variable.
int sum = 0;
for (int i = 1; i <= 10; i++) {
sum = sum + i;
}
Often a programmer reuses a temporary variable with the mistaken notion that it will save memory or increase performance. That was likely true in the 1980s, but it is rarely true today. Reusing the same temporary variable is essentially having poorly named variables, and that makes your code worse. Simply split the temporary assignments into their own variables.
When a temporary variable is assigned to more than once, it is often a sign that the variables have more than one responsibility. This violates the single responsibility principle and leads to poor, confusing code.
Simple Example
Let’s consider a very simple example where a developer is calculating various properties of a circle:
double temp = Math.PI * radius * radius;
Console.WriteLine(temp);
temp = 2 * Math.PI * radius;
Console.WriteLine(temp);
The code is correct, but reusing the temp
variable has confused what is actually happening in the code. Also, the temp
variable has two responsibilities which is wrong. We can make the code more clear by splitting the temporary variable assignments into separate assignments:
double area = Math.PI * radius * radius;
Console.WriteLine(area);
double circumference = 2 * Math.PI * radius;
Console.WriteLine(circumference);
Each variable now has a single responsibility, and each variable has a clear name. This can lead to more insights as well and further refactorings.
References
- Fowler, M. et al. Refactoring: Improving the Design of Existing Code. Pearson Education, 2012. Web. Addison-Wesley Object Technology Series.