是怎樣?
重構前:
double getPrice() {
int basePrice = _quantity * _itemPrice;
double discountFactor;
if (basePrice > 1000) {
discountFactor = 0.95;
} else {
discountFactor = 0.98;
}
return basePrice * discountFactor;
}
重構后:
>```Java
double getPrice() {
return basePrice() * discountFactor();
}
private double discountFactor() {
if (basePrice() > 1000) {
return 0.95;
} else {
return 0.98;
}
}
private int basePrice() {
return _quantity * _itemPrice;
}
如何做?
- 先給這兩個臨時變量添加 final 修飾詞確保他們只被賦值一次
final int basePrice = _quantity * _itemPrice;
final double discountFactor;
- 選中 basePrice, 右鍵 -> refactor -> Replace Temp With Query
double getPrice() {
final double discountFactor;
if (basePrice() > 1000) {
discountFactor = 0.95;
} else {
discountFactor = 0.98;
}
return basePrice() * discountFactor;
}
private int basePrice() {
return _quantity * _itemPrice;
}
- 運行測試。
- 接著開始替換discountFactor變量。這里不能直接用Replace Temp With Query, 先選中如下代碼,
final double discountFactor;
if (basePrice() > 1000) {
discountFactor = 0.95;
} else {
discountFactor = 0.98;
}
用 Extract Method(cmd + opt + m) 將他們提煉到一個獨立的方法中去, 由于后續還需要用到discountFactor的值,所以這里在Extract Method的時候,要提供一個返回值,不過android studio 會自動做完這個步驟。執行完成之后:
private double discountFactor() {
final double discountFactor;
if (basePrice() > 1000) {
discountFactor = 0.95;
} else {
discountFactor = 0.98;
}
return discountFactor;
}
運行測試。對discountFactor這個方法可以再簡化一下,去掉臨時變量,運行測試。
private double discountFactor() {
if (basePrice() > 1000) {
return 0.95;
} else {
return 0.98;
}
}
- 現在getPrice方法像這樣:
double getPrice() {
final double discountFactor = discountFactor();
return basePrice() * discountFactor;
}
去掉臨時變量,運行測試。
double getPrice() {
return basePrice() * discountFactor();
}