Replace Temp with Query

You are using a temporary variable to hold the result of an expression.

Extract the expression into a method. Replace all references to the temp with the expression. The new method can then be used in other methods.

double basePrice = _quantity * _itemPrice;
if (basePrice > 1000)
  return basePrice * 0.95;
  return basePrice * 0.98;


if (basePrice() > 1000)
  return basePrice() * 0.95;
  return basePrice() * 0.98;
double basePrice() {
  return _quantity * _itemPrice;


Side Effects

Paul Haahr pointed out that you can't do this refactoring if the code in between the the assignment to the temp and the use of the temp changes the value of the expression that calculates the temp. In these cases the code is using the temp to snapshot the value of the temp when it's assigned. The name of the temp should convey this fact (and you should change the name if it doesn't).

He also pointed out that it is easy to forget that creating a reference object is a side effect, while creating a value object isn't.