Replace Temp with Query <IMG SRC = "http://www.refactoring.com/catalog/updated.gif" border=0>
2003. 8. 3. 12:35
Replace Temp with Query
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;
else
return basePrice * 0.98;
![](http://www.refactoring.com/catalog/arrow.gif)
if (basePrice() > 1000)
return basePrice() * 0.95;
else
return basePrice() * 0.98;
...
double basePrice() {
return _quantity * _itemPrice;
}
For more information see page 120 of Refactoring
Additional Comments
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.
Contributors
- Paul Haahr
***** 아름다운프로님에 의해서 게시물 복사 + 카테고리변경되었습니다 (2003-12-18 17:27)