你的程序以一個臨時變量(temp)保存某一表達式的運算結果.
將這個表達式提煉到一個獨立函數中.將這個臨時變量的所有[被引用點]替換為[對新函數的調用].新函數可被其他函數使用.
double basePrice = _quantity * _itemPrice;
if(basePrice > 1000)
return basePrice * 0.95;
else
return basePrice * 0.98;
| |
| |
\ /
if(basePrice() > 1000)
return basePrice() * 0.95;
else
return base() * 0.98;
...
double basePrice() {
return _quantity * _itemPrice;
}