是怎樣软驰?
重構(gòu)前:
double getPrice() {
int basePrice = _quantity * _itemPrice;
double discountFactor;
if (basePrice > 1000) {
discountFactor = 0.95;
} else {
discountFactor = 0.98;
}
return basePrice * discountFactor;
}
重構(gòu)后:
>```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;
}
如何做?
- 先給這兩個(gè)臨時(shí)變量添加 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;
}
- 運(yùn)行測(cè)試沿腰。
- 接著開始替換discountFactor變量溪猿。這里不能直接用Replace Temp With Query, 先選中如下代碼,
final double discountFactor;
if (basePrice() > 1000) {
discountFactor = 0.95;
} else {
discountFactor = 0.98;
}
用 Extract Method(cmd + opt + m) 將他們提煉到一個(gè)獨(dú)立的方法中去逝慧, 由于后續(xù)還需要用到discountFactor的值截驮,所以這里在Extract Method的時(shí)候,要提供一個(gè)返回值快集,不過android studio 會(huì)自動(dòng)做完這個(gè)步驟贡羔。執(zhí)行完成之后:
private double discountFactor() {
final double discountFactor;
if (basePrice() > 1000) {
discountFactor = 0.95;
} else {
discountFactor = 0.98;
}
return discountFactor;
}
運(yùn)行測(cè)試。對(duì)discountFactor這個(gè)方法可以再簡(jiǎn)化一下个初,去掉臨時(shí)變量乖寒,運(yùn)行測(cè)試。
private double discountFactor() {
if (basePrice() > 1000) {
return 0.95;
} else {
return 0.98;
}
}
- 現(xiàn)在getPrice方法像這樣:
double getPrice() {
final double discountFactor = discountFactor();
return basePrice() * discountFactor;
}
去掉臨時(shí)變量院溺,運(yùn)行測(cè)試楣嘁。
double getPrice() {
return basePrice() * discountFactor();
}