Motivation
局部变量会使代码难以被提炼,所以应该尽可能将他们替换为查询式。
另外,ReplaceTemp with Query也是Extract Method的必要步骤。
Mechanics
1 如果临时变量被赋值多次,则应用Split Temporary Variable,将他分割成多个变量,每个新的变量只被赋值一次。
2 对每一个临时变量,提取查询函数,然后替换。(如果查询函数有副作用,应再应用重构Separate Query from Modifler)
Eclipse refactor菜单中没有直接的对应项,
不过仍可以简单的组合[ExtractMethod] + [Inline] 完成对应的重构
// 原始代码,其中临时变量basePrice和discountFactor明显是可以应用ReplaceTemp with Querydouble getPrice() { final int basePrice = _quantity * _itemPrice; final double discountFactor; if (basePrice > 1000)discountFactor = 0.95; else discountFactor = 0.98; return basePrice *discountFactor; }
// 选中_quantity * _itemPrice,应用[Extract Method]
double getPrice() {
final int basePrice = basePrice();
final double discountFactor;
if (basePrice > 1000)discountFactor = 0.95;
else discountFactor = 0.98;
return basePrice *discountFactor;
}
private int basePrice() {
return _quantity * _itemPrice;
}
// 选中basePrice, 应用[Inline]
double getPrice() {
finalint basePrice =basePrice();
final double discountFactor;
if (basePrice() > 1000) discountFactor = 0.95;
else discountFactor = 0.98;
return basePrice() * discountFactor;
}
private int basePrice() {
return_quantity * _itemPrice;
}
类似的,可以继续对discountFactor应用上面方法,仍旧只是鼠标右键+左键的问题。
相关代码包可以从 Here获取(上传的资源还未刷新,等刷新后更新地址)
- 1楼crylearner1小时前
- 添加重构实例代码的下载地址:nhttp://download.csdn.net/detail/crylearner/5244305