重构-改善既有代码的设计完整笔记系列之9 - 简化条件表达式

  • 9.1 Decompose Conditional(分解条件表达式)
  • 9.2 Consolidate Conditional Expression(合并条件表达式)
  • 9.3 Consolidate Duplicate Conditional Fragments(合并重复的条件片段)
  • 9.4 Remove Control Flag(移除控制标记)
  • 9.5 Replace Nested Conditional with Guard Clauses(以卫语句取代嵌套条件表达式)
  • 9.6 Replace Conditional with Polymorphism(以多态取代条件表达式)
  • 9.7 Introduce Null Object(引入Null对象)
  • 9.8 Introduce Assertion(引入断言)

9.1 Decompose Conditional(分解条件表达式)

分解为多个独立函数,根据每个小块代码的用途,为分解的新函数命名,从而更清楚的表达意图

if (date.before (SUMMER_START) || date.after(SUMMER_END))
    charge = quantity * _winterRate + _winterServiceCharge;
else charge = quantity * _summerRate;

//转变:
if (notSummer(date))
    charge = winterCharge(quantity);
else 
    charge = summerCharge (quantity);

private boolean notSummer(Date date) {
    return date.before (SUMMER_START) || date.after(SUMMER_END);
}

private double summerCharge(int quantity) {
    return quantity * _summerRate;
}

private double winterCharge(int quantity) {
    return quantity * _winterRate + _winterServiceCharge;
}

9.2 Consolidate Conditional Expression(合并条件表达式)

一系列条件都得到相同结果。则将这些测试合并为一个条件表达式。

double disabilityAmount() {
    if (_seniority < 2) return 0;
    if (_monthsDisabled > 12) return 0;
    if (_isPartTime) return 0;

// compute the disability amount
double disabilityAmount() {
    if (isNotEligableForDisability()) return 0;

9.3 Consolidate Duplicate Conditional Fragments(合并重复的条件片段)

在条件表达式的每个分支上有着相同的一段代码。将这段重复代码移到条件表达式之外.

if (isSpecialDeal()) {
    total = price * 0.95;
    send();
}
else {
    total = price * 0.98;
    send();
}
//变为:
if (isSpecialDeal())
    total = price * 0.95;
else
    total = price * 0.98;
send();


9.4 Remove Control Flag(移除控制标记)

//以break或return语句取代控制标记。

    void checkSecurity(String[] people) {
        boolean found = false;
        for (int i = 0; i < people.length; i++) {
            if (!found) {
                if (people[i].equals("Don")) {
                    sendAlert();
                    found = true;
                }
                if (people[i].equals("John")) {
                    sendAlert();
                    found = true;
                }
            }
        }
    }
//替换:
    void checkSecurity(String[] people) {
        for (int i = 0; i < people.length; i++) {
            if (people[i].equals("Don")) {
                sendAlert();
                break;
            }
            if (people[i].equals("John")) {
                sendAlert();
                break;
            }
        }
    }

//另外,return也需要合理使用
    void checkSecurity(String[] people) {
        String found = "";

        for (int i = 0; i < people.length; i++) {
            if (found.equals("")) {
                if (people[i].equals("Don")) {
                    sendAlert();
                    found = "Don";
                }
                if (people[i].equals("John")) {
                    sendAlert();
                    found = "John";
                }
            }
        }
        someLaterCode(found);
    }
//改成:
    String foundMiscreant(String[] people) {
        for (int i = 0; i < people.length; i++) {
            if (people[i].equals("Don")) {
                sendAlert();
                return "Don";
            }
            if (people[i].equals("John")) {
                sendAlert();
                return "John";
            }
        }
        return "";
    }

9.5 Replace Nested Conditional with Guard Clauses(以卫语句取代嵌套条件表达式)

    double getPayAmount() {
        double result;
        if (_isDead)
            result = deadAmount();
        else {
            if (_isSeparated)
                result = separatedAmount();
            else {
                if (_isRetired)
                    result = retiredAmount();
                else
                    result = normalPayAmount();

            }
            
        }
        return result;
    }
//改成
    double getPayAmount() {
        double result;
        if (_isDead)
            return deadAmount();
        if (_isSeparated)
            return separatedAmount();
        if (_isRetired)
            result = retiredAmount();
        else
            result = normalPayAmount();
        return result;
    }

9.6 Replace Conditional with Polymorphism(以多态取代条件表达式)

一个条件表达式,它根据对象类型的丌同而选择丌同的行为。
将这个条件表达式的每个分支放进一个子类的覆写函数中,然后将原始函数声明为抽象函数。
比如将以下条件都转换成子类

    double getSpeed() {
        switch (_type) {
        case EUROPEAN:
            return getBaseSpeed();
        case AFRICAN:
            return getBaseSpeed() - getLoadFactor() * _numberOfCoconuts;
        case NORWEGIAN_BLUE:
            return (_isNailed) ? 0 : getBaseSpeed(_voltage);
        }
        throw new RuntimeException("Should be unreachable");
    }

9.7 Introduce Null Object(引入Null对象)

9.8 Introduce Assertion(引入断言)

某一段代码需要对程序状态做出某种假设。以断言明确表现这种假设。

使用断言明确标明对输入条件的严格要求和限制;
断言可以辅助交流和调试。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值