场景:
表达式非常复杂且难以阅读
解决方案
使用临时变量将表达式分解成为容易管理的形式
注意点
如果可以使用Extract Method进行提取的时候,尽可能使用Extract Method提取,Extract Method提取之后可以全局调用,而解释型变量的使用范围有局限,如果局部变量使得Extract Method无法进行的时候才考虑引入解释型变量
实现步骤
- 声明一个final 临时变量,将分解的表达式中的部分赋值给它
- 将表达式中的”运算结果“,替换为此临时变量
- 编译测试
- 重复,处理表达式的其他部分
实例代码
- 原始代码
doublePrice(){
return _quantity * _itemPrice -
Math.max(0,_quantity - 500) * _itemPrice * 0.05 +
Math.min(_quantity * itemPrice * 0.01,100.0);
}
- 提取底价 数量 * 单价
final double basePrice = _quantity * _itemPrice;
return basePrice -
Math.max(0,_quantity - 500) * _itemPrice * 0.05 +
Math.min(_quantity * itemPrice * 0.01,100.0);
- 重复操作...
final double basePrice = _quantity * _itemPrice;
final double discount = Math.max(0,_quantity - 500) * itemPrice * 0.05;
final doubel skining = Math.min(basePrice * 0.01,100.0);
return basePrice - discount + skining;