Replace Temp With Query - refactor with android studio

是怎样?

重构前:

double getPrice() {
    int basePrice = _quantity * _itemPrice;
    double discountFactor;
    if (basePrice > 1000) {
        discountFactor = 0.95;
    } else {
        discountFactor = 0.98;
    }
    return basePrice * discountFactor;
}
   
重构后:
>```Java
    double getPrice() {
        return basePrice() * discountFactor();
    }
    private double discountFactor() {
        if (basePrice() > 1000) {
            return 0.95;
        } else {
            return 0.98;
        }
    }
    private int basePrice() {
        return _quantity * _itemPrice;
    }
如何做?
  • 先给这两个临时变量添加 final 修饰词确保他们只被赋值一次
        final int basePrice = _quantity * _itemPrice;
        final double discountFactor;
  • 选中 basePrice, 右键 -> refactor -> Replace Temp With Query
   double getPrice() {
        final double discountFactor;
        if (basePrice() > 1000) {
            discountFactor = 0.95;
        } else {
            discountFactor = 0.98;
        }
        return basePrice() * discountFactor;
    }

    private int basePrice() {
        return _quantity * _itemPrice;
    }
  • 运行测试。
  • 接着开始替换discountFactor变量。这里不能直接用Replace Temp With Query, 先选中如下代码,
        final double discountFactor;
        if (basePrice() > 1000) {
            discountFactor = 0.95;
        } else {
            discountFactor = 0.98;
        }

用 Extract Method(cmd + opt + m) 将他们提炼到一个独立的方法中去, 由于后续还需要用到discountFactor的值,所以这里在Extract Method的时候,要提供一个返回值,不过android studio 会自动做完这个步骤。执行完成之后:

    private double discountFactor() {
        final double discountFactor;
        if (basePrice() > 1000) {
            discountFactor = 0.95;
        } else {
            discountFactor = 0.98;
        }
        return discountFactor;
    }

运行测试。对discountFactor这个方法可以再简化一下,去掉临时变量,运行测试。

    private double discountFactor() {
        if (basePrice() > 1000) {
            return 0.95;
        } else {
            return 0.98;
        }
    }
  • 现在getPrice方法像这样:
    double getPrice() {
        final double discountFactor = discountFactor();
        return basePrice() * discountFactor;
    }

去掉临时变量,运行测试。

    double getPrice() {
        return basePrice() * discountFactor();
    }

详细阅读参考《重构》(看云)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值