文章目录
  1. 1. Decompose Conditional(分解条件表达式)
    1. 1.1. Before Refactoring
    2. 1.2. After Refactoring
  2. 2. Consolidate Conditional Expression(合并条件表达式)
    1. 2.1. Before Refactoring
    2. 2.2. After Refactoring
  3. 3. Consolidate Duplicate Conditional Fragments(合并重复的条件判断)
    1. 3.1. Before Refactoring
    2. 3.2. After Refactoring
  4. 4. Remove Control Flag(移除控制标记)
    1. 4.1. Before Refactoring
    2. 4.2. After Refactoring
  5. 5. Replace Nested Conditional with Guard Clauses(以卫语句取代嵌套条件表达式)
    1. 5.1. Before Refactoring
    2. 5.2. After Refactoring
  6. 6. Replace Conditional with Polymorphism(以多态取代条件表达式)
    1. 6.1. Before Refactoring
    2. 6.2. After Refactoring
  7. 7. Introduce Null Object(引入Null对象)
    1. 7.1. Before Refactoring
    2. 7.2. After Refactoring
  8. 8. Introduce Assertion(引入断言)
    1. 8.1. Before Refactoring
    2. 8.2. After Refactoring

条件逻辑有可能十分复杂,因此本章提供一些重构手法,专门用来简化它们。

Decompose Conditional(分解条件表达式)

有一个复杂的条件(if-then-else)语句。

应该从if, then, else 三个段落中分别提炼出独立函数。

Before Refactoring

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

After Refactoring

if (notSummer(date)) {
    charge = winterCharge(quantity);
}else {
    charge = summerCharge(quantity);
}

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

有一系列条件测试,都得到相同结果。

应该将这些测试合并为一个条件表达式,并将这个条件表达式提炼为一个独立函数。

Before Refactoring

double disabilityAmount() {
    if(_seniority < 2) return 0;
    if(_monthsDisabled < 2) return 0;
    if(_isPartTime < 2) return 0;
    //compute the disability amount
}

After Refactoring

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

Consolidate Duplicate Conditional Fragments(合并重复的条件判断)

在条件表达式的每个分支上有着相同的一段代码。

应该将这段重复代码搬移到条件表达式之外。

Before Refactoring

if (isSpecialDeal()) {
    total = price * 0.95;
    send();
} else {
    total = price * 0.98;
    send();
}

After Refactoring

if (isSpecialDeal()) {
    total = price * 0.95;
} else {
    total = price * 0.98;
}
send();

Remove Control Flag(移除控制标记)

在一系列布尔表达式中,某个变量带有“控制标记”到作用。

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

Before Refactoring

String foundMiscreant(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";
            }
        }
    }
    return found;
}

After Refactoring

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 "";
}

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

函数中的条件逻辑使人难以看清正常的执行路径。

应该使用卫语句表现所有特殊情况。

Before Refactoring

double getPayAmount() {
    double result;
    if (_isDead) {
        result = deadAmount();
    } else {
        if (_isSeparated {
            result = separatedAmount();
        } else {
            result = normalPayAmount();
        }
    }
    return result;
}

After Refactoring

double getPayAmount() {
    if (_isDead) {
        return deadAmount();
    }
    if (_isSeparated) {
        return separatedAmount();
    }
    if (_isRetired) {
        return retiredAmount();
    }
    return normalPayAmount();
}

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

一个条件表达式,根据对象类型不同来选择不同的行为。

应该将这个条件表达式的每个分支放进一个子类内的覆写函数中,然后将原始函数声明为抽象函数。

Before Refactoring

class Employee...
    int payAmount() {
        switch(getType()) {
            case EmployeeType.ENGINEER:
                return _mongthlySalary;
            case EmployeeType.SALESMAN:
                return _mongthlySalary + _commission;
            case EmployeeType.MANAGER:
                return _mongthlySalary + _bonus;
            default:
                throw new RuntimeException();
        } 
    }

After Refactoring

class Employee...
    int payAmount() {
        return _type.payAmount(this);
    }

class Salesman..
    int payAmount(Employee emp) {
        return emp.getMonthlySalary() + emp.getCommission();
    }
......

Introduce Null Object(引入Null对象)

程序中你需要再三检查某个对象是否为null

应该将null值替换为null对象。

Before Refactoring

Customer customer = site.getCustomer();
BillingPlan plan;
if (customer == null) {
    plan = BillingPlan.basic();
} else {
    plan = customer.getPlan();
}
...
String customerName;
if (customer == null) {
    customerName = "occupant";
} else {
    customerName = customer.getName();
}

After Refactoring

class NullCustomer extends Customer {
    public boolean isNull() {
        return true;
    }
    static Customer newNull() {
        return new NullCustomer();
    }
    public String getName() {
        return "occupant";
    }
    public void setPlan(BillingPlan arg) {

    }
}

class Site....
    Customer getCustomer() {
        return (_customer == null) ? Customer.newNull():_customer;
    }

Customer customer = site.getCustomer();
BillingPlan plan = customer.getPlan();
...
String customerName = customer.getName();

Introduce Assertion(引入断言)

某一段代码需要对程序状态做出某种假设。

应该以断言明确表现这种假设。

Before Refactoring

double getExpenseLimit() {
    return (_expenseLimit != NULL_EXPENSE)?_expenseLimit:_primaryProject.getMemberExpenseLimit();
}

After Refactoring

double getExpenseLimit() {
    Assert.isTrue(_expenseLimit != NULL_EXPENSE || _primaryProject != null)
    return (_expenseLimit != NULL_EXPENSE)?_expenseLimit:_primaryProject.getMemberExpenseLimit();
}
文章目录
  1. 1. Decompose Conditional(分解条件表达式)
    1. 1.1. Before Refactoring
    2. 1.2. After Refactoring
  2. 2. Consolidate Conditional Expression(合并条件表达式)
    1. 2.1. Before Refactoring
    2. 2.2. After Refactoring
  3. 3. Consolidate Duplicate Conditional Fragments(合并重复的条件判断)
    1. 3.1. Before Refactoring
    2. 3.2. After Refactoring
  4. 4. Remove Control Flag(移除控制标记)
    1. 4.1. Before Refactoring
    2. 4.2. After Refactoring
  5. 5. Replace Nested Conditional with Guard Clauses(以卫语句取代嵌套条件表达式)
    1. 5.1. Before Refactoring
    2. 5.2. After Refactoring
  6. 6. Replace Conditional with Polymorphism(以多态取代条件表达式)
    1. 6.1. Before Refactoring
    2. 6.2. After Refactoring
  7. 7. Introduce Null Object(引入Null对象)
    1. 7.1. Before Refactoring
    2. 7.2. After Refactoring
  8. 8. Introduce Assertion(引入断言)
    1. 8.1. Before Refactoring
    2. 8.2. After Refactoring