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

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获取(上传的资源还未刷新,等刷新后更新地址)




评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值