范例(Examples)
我们从一个简单计算开始:
double price() {
//price is base price - quantity discount + shipping
return _quantity * _itemPrice -
Math.max(0, _quantity - 500) * _itemPrice * 0.05 +
Math.min(_quantity * _itemPrice * 0.1, 100.0);
}
这段代码还算简单,不过我可以让它变得更容易理解.首先我发现,底价(base price)等于数量(quantity)乘以单价(item price).于是我把这一部分计算的结果放进一个临时变量中:
double price() {
//price is base price - quantity discount + shipping
final double basePrice = _quantity * _itemPrice;
return basePrice -
Math.max(0, _quantity - 500) * _itemPrice * 0.05 +
Math.min(_quantity * _itemPrice * 0.1, 100.0);
}
稍后也用上了[数量乘以单价]运算结果,所以我同样将它替换为basePrice临时变量:
double price() {
//price is base price - quantity discount + shipping
final double basePrice = _quantity * _itemPrice;
return basePrice -
Math.max(0, _quantity - 500) * _itemPrice * 0.05 +
Math.min(basePrice * 0.1, 100.0);
}
然后,我将批发折扣(quantity discount)的计算提炼出来,将结果赋予临时变量quantityDiscount:
double price() {
//price is base price - quantity discount + shipping
final double basePrice = _quantity * _itemPrice;
final double quantityDiscount = Math.max(0, _quantity - 500) *
_itemPrice * 0.05;
return basePrice - quantityDiscount +
Math.min(basePrice * 0.1, 100.0);
}
最后,我再把运费(shipping)计算提炼出来,将运算结果赋予临时变量shipping.同时我还可以删掉代码中的注释,因为现在代码已经可以完美表达自己的意义了:
double price() {
//price is base price - quantity discount + shipping
final double basePrice = _quantity * _itemPrice;
final double quantityDiscount = Math.max(0, _quantity - 500) *
_itemPrice * 0.05;
final double shipping = Math.min(basePrice * 0.1, 100.0);
return basePrice - quantityDiscount + shipping;
}