范例(Examples)
首先,我從一個簡單函數開始:
double getPrice() {
int basePrice = _quantity * _itemPrice;
double discountFactor;
if(basePrice > 1000) discountFactor = 0.95;
else discountFactor = 0.98;
return basePrice * discountFactor;
}
我希望將兩個臨時變量都替換掉.當然,每次一個.
盡管這里的代碼十分清楚,我還是先把臨時變量聲明為final,檢查它們是否的確只被賦值一次:
double getPrice() {
final int basePrice = _quantity * _itemPrice;
final double discountFactor;
if(basePrice > 1000) discountFactor = 0.95;
else discountFactor = 0.98;
return basePrice * discountFactor;
}
這么一來,如果有任何問題,編譯器就會警告我.之所以先做這件事,因為如果臨時變量不知被賦值一次,我就不該進行這項重構.接下來我開始替換臨時變量,每次一個.首先我把賦值(assignment)動作的右側表達式提煉出來:
double getPrice() {
final int basePrice = basePrice();
final double discountFactor;
if(basePrice > 1000) discountFactor = 0.95;
else discountFactor = 0.98;
return basePrice * discountFactor;
}
private int basePrice() {
return _quantity * _itemPrice;
}
編譯并測試,然后開始使用Inline Temp(119).首先把臨時變量basePrice的第一個引用點替換掉:
double getPrice() {
final int basePrice = basePrice();
final double discountFactor;
if(basePrice() > 1000) discountFactor = 0.95;
else discountFactor = 0.98;
return basePrice * discountFactor;
}
編譯,測試,下一個.由于[下一個]已經是basePrice的最后一個引用點,所以我把basePrice臨時變量的聲明式一并摘除:
double getPrice() {
final double discountFactor;
if(basePrice() > 1000) discountFactor = 0.95;
else discountFactor = 0.98;
return basePrice() * discountFactor;
}
搞定basePrice之后,我再以類似辦法提煉出一個discountFactor():
double getPrice() {
final double discountFactor = discountFactor();
return basePrice() * discountFactor;
}
private double discountFactor() {
if(basePrice() > 1000) return 0.95;
else return 0.98;
}
你看,如果我沒有把臨時變量basePrice替換為一個查詢式,將多么難以提煉discountFactor()!
最終,getPrice()變成了這樣:
double getPrice() {
return basePrice() * discountFactor();
}