美文网首页
Replace Temp With Query - refact

Replace Temp With Query - refact

作者: 大姨夫斯基 | 来源:发表于2017-06-16 22:14 被阅读14次

    是怎样?

    重构前:

    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();
        }
    

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

    相关文章

      网友评论

          本文标题:Replace Temp With Query - refact

          本文链接:https://www.haomeiwen.com/subject/yrtmqxtx.html