重构之重新组织函数(Introduce Explaining Variable)

Introduce Explaining Variable

概述

将复杂表达式的结果放进一个临时变量,以此变量名称来解释表达式用途。

动机(Motivation)

表达式有可能非常复杂而难以阅读,临时变量可以帮助你将表达式分解为比较容易管理的形式。

作法(Mechanics)

1、声明一个final临时变量,将待分解之复杂表达式中的一部分动作的运算结果赋值给它。

2、将表达式中的运算结果这一部分,替换为上述临时变量。

如果被替换的这一部分在代码中重复出现,你可以每次一个,逐一替换。

public class IntroduceExplainingVariable {

    double _width,_higth;

    //before introducing
    public double getPrice()
    {
        return _width * _higth - Math.max(0, _width - 1000) * _higth * 0.03 + Math.min(_width * _higth * 0.1, 100);
    }

    //after introducing
    public double getPriceAdvanced()
    {
        return normalPrice() - quantityDiscount() + shipping();
    }

    public double normalPrice()
    {
        return _width * _higth;
    }

    public double quantityDiscount()
    {
        return Math.max(0, _width - 1000) * _higth * 0.03;
    }

    //邮费
    public double shipping()
    {
        return Math.min(normalPrice() * 0.1, 100);
    }
}
原文地址:https://www.cnblogs.com/newbee0101/p/11970467.html