您的位置:首页 > 编程语言 > Java开发

使用Eclipse重构代码——Replace Temp with Query

2013-04-10 23:31 495 查看
Motivation

局部变量会使代码难以被提炼,所以应该尽可能将他们替换为查询式。

另外,ReplaceTemp with Query也是Extract Method的必要步骤。

Mechanics

1 如果临时变量被赋值多次,则应用Split Temporary Variable,将他分割成多个变量,每个新的变量只被赋值一次。

2 对每一个临时变量,提取查询函数,然后替换。(如果查询函数有副作用,应再应用重构Separate Query from Modifler)

Eclipse refactor菜单中没有直接的对应项,

不过仍可以简单的组合[ExtractMethod] + [Inline] 完成对应的重构

// 原始代码,其中临时变量basePrice和discountFactor明显是可以应用ReplaceTemp with Query
double 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() {
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;
}

类似的,可以继续对discountFactor应用上面方法,仍旧只是鼠标右键+左键的问题。

相关代码包可以从 Here获取(上传的资源还未刷新,等刷新后更新地址)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: