Smell Detail

Temporary Field

临时字段

Object-Orientation Abusers

Some fields in an object only have meaningful values in specific situations.

Define

Introduction

Temporary Fields appear when certain fields of an object are only used in specific algorithms or situations. They make code harder to understand because you expect all fields of an object to be generally meaningful.

Key Identifiers

  • Some fields are only referenced in one or two methods
  • Field values are null/empty/meaningless most of the time
  • Object state appears inconsistent or partially populated
  • It's unclear why the field exists when reading the class

Refactoring Suggestions

  1. Extract Class: Move temporary fields and related methods into a dedicated helper class
  2. Introduce Null Object: Use a Null Object to handle special cases instead of optional fields
  3. Use Local Variables: Pass temporary data as parameters or keep it local within methods
  4. Strategy Pattern: Use different strategy objects for varying scenarios instead of conditional fields

Explanation

Temporary fields should be extracted into a dedicated class or converted into local variables. This keeps the object's state consistent and predictable.

Code Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import java.util.*;
class Calculator {
private double operand1;
private double operand2;
private char operation;
// These fields are only used in complex calculations
private double tempResult;
private double intermediateValue;
private boolean isComplexCalculation;
private List<Double> calculationSteps;
public Calculator() {
this.calculationSteps = new ArrayList<>();
}
public double calculate(double a, double b, char op) {
operand1 = a;
operand2 = b;
operation = op;
if (op == '^') {
// Only use these temporary fields during power operations
isComplexCalculation = true;
tempResult = 1;
intermediateValue = a;
calculationSteps.clear();
for (int i = 0; i < b; i++) {
tempResult *= intermediateValue;
calculationSteps.add(tempResult);
}
return tempResult;
} else {
isComplexCalculation = false;
// These fields are meaningless during simple operations
tempResult = 0;
intermediateValue = 0;
calculationSteps.clear();
switch (op) {
case '+': return a + b;
case '-': return a - b;
case '*': return a * b;
case '/': return a / b;
default: return 0;
}
}
}
public List<Double> getCalculationSteps() {
// This method only makes sense after complex calculations
return new ArrayList<>(calculationSteps);
}
public double getTempResult() {
// This field is only meaningful during complex calculations
return tempResult;
}
}