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