临时字段
Some fields in an object only have meaningful values in specific situations.
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.
Temporary fields should be extracted into a dedicated class or converted into local variables. This keeps the object's state consistent and predictable.
import java.util.*;class Calculator {private double operand1;private double operand2;private char operation;// These fields are only used in complex calculationsprivate 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 operationsisComplexCalculation = 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 operationstempResult = 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 calculationsreturn new ArrayList<>(calculationSteps);}public double getTempResult() {// This field is only meaningful during complex calculationsreturn tempResult;}}