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

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,790评论 0 33
  • importUIKit classViewController:UITabBarController{ enumD...
    明哥_Young阅读 3,942评论 1 10
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,823评论 18 399
  • Java经典问题算法大全 /*【程序1】 题目:古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子...
    赵宇_阿特奇阅读 1,963评论 0 2
  • 怎么办?怎么办?我们迷路了?天渐黑,尝试几次寻找出路,未果!团长说,我们还是先去找点食物,以防今晚被困山里!孩子一...
    大马虎遇见了小怪物阅读 417评论 0 2