美文网首页
《重构》- 简化条件表达式

《重构》- 简化条件表达式

作者: nimw | 来源:发表于2018-11-20 20:04 被阅读5次

一. Decompose Conditional(分解条件表达式)

介绍

  1. 场景
    你有一个复杂的条件(if-then-else)语句。
  2. 手法
    ifthenelse三个段落中分别提炼出独立函数。

范例

重构前

class Production{
  price() {
    if(date.before(this.SUMMER_START) || date.after(this.SUMMER_END)) {
      return quantity * this._winterRate + this._winterServiceCharge
    } else {
      return quantity * _summerRate
    }
  }
}

重构后

class Production{
  price(date) {
    if(this.notSummer(date)) {
      return this.winterCharge(quantity)
    } else {
      return this.summerCharge(quantity)
    }
  }

  notSummer(date) {
   return date.before(this.SUMMER_START) || date.after(this.SUMMER_END)
  }

  winterCharge(quantity) {
   return quantity * this._winterRate + this._winterServiceCharge
  }

  summerCharge(quantity) {
    return quantity * _summerRate
  }
 }

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

  1. 场景
    你有一系列条件测试,都得到相同结果。
  2. 手法
    将这些测试合并为一个条件表达式,并将这个条件表达式提炼成为一个独立函数。

范例

  1. 使用逻辑或
    重构前
  disabilityAmount() {
    if(this._seniority < 2) return 0
    if(this._monthsDisabled > 12) return 0
    if(this._isPartTime) return 0
    // compute the disability amount
    //...
  }

重构后

  disabilityAmount() {
    if(this.isNotEligibleForDisability()) return 0
    // compute the disability amount
    //...
  }

  isNotEligibleForDisability() {
    return ((this._seniority < 2) || (this._monthsDisabled > 12) || (this._isPartTime))
  }
  1. 使用逻辑与
    重构前
  if(this.onVacation()) {
    if(this.lengthOfService() > 10) {
      return 1
    }
  }
  return 0.5

重构后

  return (this.onVacation() && this.lengthOfService() > 10) ? 1 : 0.5

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

介绍

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

范例

重构前

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

重构后

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

四. Remove Control Flag(移除控制标记)

介绍

  1. 场景
    在一系列布尔表达式中,某个变量带有“控制标记”的作用。
  2. 手法
    break语句或者return语句取代控制标记。

动机

  1. 人们之所以使用控制标记,因为结构化编程原则告诉他们:每个子程序只能有一个入口和一个出口。
  2. 我赞同“单一入口”原则,但是“单一出口”原则会让你在代码中加入讨厌的控制标记,大大降低条件表达式的可读性。这就是编程语言提供break语句和continue语句的原因:用它们跳出复杂的条件语句。

范例

  1. break取代简单的控制标记

重构前

function checkSecurity(peoples) {
  let found = false
  for(let i = 0; i < peoples.length; i++) {
    if(!found) {
      if(peoples[i] === 'Don' || peoples[i] === 'John') {
        sendAlert()
        found = true
      }
    }
  }
}

重构后

function checkSecurity(peoples) {
  for(let i = 0; i < peoples.length; i++) {
    if(peoples[i] === 'Don' || peoples[i] === 'John') {
      sendAlert()
      break;
    }
  }
}
  1. return返回控制标记

重构前

function checkSecurity(peoples) {
  let found = ''
  for(let i = 0; i < peoples.length; i++) {
    if(!found) {
      if(peoples[i] === 'Don' || peoples[i] === 'John') {
        sendAlert()
        found = peoples[i]
      }
    }
  }
  someLaterCode(found)
}

重构后

function checkSecurity(peoples) {
  const found = foundMiscreant(peoples)
  someLaterCode(found)
}

function foundMiscreant(peoples) {
  for(let i = 0; i < peoples.length; i++) {
    if(peoples[i] === 'Don' || peoples[i] === 'John') {
      sendAlert()
      return peoples[i]
    }
  }
  return ''
}

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

介绍

  1. 场景
    函数中的条件逻辑使人难以看清正常的执行路径。
  2. 手法
    使用卫语句表现所有特殊情况。

动机

  1. 条件表达式通常有两种表现形式。第一种形式是:所有分支都属于正常行为。第二种形式则是:条件表达式提供的答案中只有一种是正常行为,其他都是不常见的情况。
  2. 如果两条分支都是正常行为,就应该使用如if...else... 的条件表达式;如果某个条件极其罕见,就应该单独检查该条件,并在该条件为真时立即从函数中返回。这样的单独检查常常被称为“卫语句”。
  3. 如今的编程语言都会强制保证每个函数只有一个入口。至于“单一出口”规则,其实并不是那么有用。在我看来,保持代码清晰才是最关键的。

范例

  1. 使用卫语句

重构前

function getPayAmount() {
  let result;
  if(_isDead) {
    result = deadAmount()
  } else {
    if(_isSeparated) {
      result = separatedAmount()
    } else {
      if(_isRetired) {
        result = retiredAomunt()
      } else {
        result = normalPayAmount()
      }
    }
  }
  return result
}

重构后

function getPayAmount() {
  if(_isDead) return deadAmount()
  if(_isSeparated) return separatedAmount()
  if(_isRetired) return retiredAomunt()
  return normalPayAmount()
}
  1. 将条件反转

重构前

function getAdjustedCapital() {
  let result = 0
  if(_capital > 0) {
    if(_intRate > 0 && _duration > 0) {
      result = (_income / _duration) * ADJ_FACTOR
    }
  }
  return result
}

重构后

function getAdjustedCapital() {
  if(_capital <= 0) return 0
  if(_intRate <= 0 || _duration <= 0) return 0
  return (_income / _duration) * ADJ_FACTOR
}

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

介绍

  1. 场景
    你手上有个条件表达式,它根据对象类型的不同而选择不同的行为。
  2. 手法
    将这个条件表达式的每个分支放进一个子类内的覆写函数中,然后将原始函数声明为抽象函数。

动机

  1. 多态最根本的好处就是:如果你需要根据对象的不同类型而采取不同的行为,多态使你不必编写明显的条件表达式。
  2. 正是因为有了多态,你会发现“类型码的switch语句”以及“基于类型名称的if-then-else语句”在面向对象程序中很少出现。

范例

重构前

class Employee {
  constructor(type) {
    this._type = type
  }

  getType() {
    return this._type.getTypeCode()
  }

  setType(arg) {
    this._type = EmployeeType.newType(arg)
  }

  payAmount() {
    switch(this.getType()) {
      case EmployeeType.ENGINEER:
        return this._monthlySalary
      case EmployeeType.SALESMAN:
        return this._monthlySalary + this._commission
      case EmployeeType.MANAGER:
        return this._monthlySalary + this._bonus
      default:
        throw new Error('Incorrect Employee') 
    }
  }
}

class EmployeeType{
  static ENGINEER = 0; //工程师
  static SALESMAN = 1; //销售员
  static MANAGER = 2; //管理者

  getTypeCode() {}

  newType() {
    switch(arg) {
      case EmployeeType.ENGINEER:
        return new Engineer()
      case EmployeeType.SALESMAN:
        return new Saleman()
      case EmployeeType.MANAGER:
        return new Manager()
      default:
        throw new Error('Incorrect Employee Code')
    }
  }
}

class Engineer extends EmployeeType {
  getTypeCode() {
    return Employee.ENGINEER
  }
}

class Manager extends EmployeeType {
  getTypeCode() {
    return Employee.MANAGER
  }
}

class Saleman extends EmployeeType{
  getTypeCode() {
    return Engineer.SALESMAN
  }
}

重构后

class Employee {
  constructor(type) {
    this._type = type
  }

  getType() {
    return this._type.getTypeCode()
  }

  setType(arg) {
    this._type = EmployeeType.newType(arg)
  }

  payAmount() {
    return this._type.payAmount()
  }
}

class EmployeeType{
  static ENGINEER = 0; //工程师
  static SALESMAN = 1; //销售员
  static MANAGER = 2; //管理者

  getTypeCode() {}

  newType() {
    switch(arg) {
      case EmployeeType.ENGINEER:
        return new Engineer()
      case EmployeeType.SALESMAN:
        return new Saleman()
      case EmployeeType.MANAGER:
        return new Manager()
      default:
        throw new Error('Incorrect Employee Code')
    }
  }

  payAmount(emp) {}
}

class Engineer extends EmployeeType {
  getTypeCode() {
    return Employee.ENGINEER
  }

  payAmount(emp) {
    return emp.getMonthlySalary()
  }
}

class Manager extends EmployeeType {
  getTypeCode() {
    return Employee.MANAGER
  }

  payAmount(emp) {
    return emp.getMonthlySalary() + emp.getCommission()
  }
}

class Saleman extends EmployeeType{
  getTypeCode() {
    return Engineer.SALESMAN
  }

  payAmount(emp) {
    return emp.getMonthlySalary() + emp.getBonus()
  }
}

七. Introduce Null Object(引入Null对象)

介绍

  1. 场景
    你需要再三检查某对象是否为null
  2. 手法
    null值替换为null对象。

动机

  1. 多态的最根本好处在于:你不必再向对象询问“你是什么类型”而后根据得到的答案调用对象的某个行为——你只管调用该行为就是了,其他的一切多态机制会为你安排妥当。
  2. 当某个字段内容是null时,多态可扮演另一个较不直观(亦较不为人所知)的用途。
  3. 空对象一定是常量,他们的任何成分都不会发生变化。因此可以使用单例模式来实现他们。

范例

重构前

class Site {
  _customer;

  getCustomer() {
    return this._customer
  }
}

class Customer {
  getName() {}

  getPlan() {}

  getHistory() {}
}

class PaymentHistory {
  getWeeksDelinquentInLastYear() {}
}

//示例代码
const customer = site.getCustomer()
const plan = customer ? customer.getPlan() : BillingPlan.basic() 
const customerName = customer ? customer.getName() : 'occupant'
const weeksDelinquent = customer ? customer.getHistory().getWeeksDelinquentInLastYear() : 0

重构后

class Site {
  _customer;

  getCustomer() {
    return this._customer ? this._customer : Customer.newNull()
  }
}

class Customer {
  static newNull() {
    return new NullCustomer();
  }

  isNull() {
    return false
  }

  getName() {}

  getPlan() {}

  getHistory() {}
}

class NullCustomer extends Customer {
  isNull() {
    return true
  }

  getName() {
    return 'occupant'
  }

  getPlan() {
    return BillingPlan.basic() 
  }

  getHistory() {
    return PaymentHistory.newNull()
  }
}

class PaymentHistory {
  static newNull() {
    return new NullPaymentHistory();
  }

  getWeeksDelinquentInLastYear() {}
}

class NullPaymentHistory extends PaymentHistory {
  getWeeksDelinquentInLastYear() {
    return 0
  }
}

//示例代码
const customer = site.getCustomer()
const plan = customer.getPlan()
const customerName = customer.getName()
const weeksDelinquent = customer.getHistory().getWeeksDelinquentInLastYear()

八. Introduce Assertion(引入断言)

介绍

  1. 场景
    某一段代码需要对程序状态做出某种假设。
  2. 手法
    以断言明确表现这种假设。

动机

  1. 常常有这样一段假设:只有当某个条件为真时,该段代码才能正常运行。例如平放根计算只对正值才能进行。
  2. 这样的假设通常并没有在代码中明确表现出来,你必须阅读整个算法才能看出。有时候程序员会以注释写出这样的假设。使用断言明确标明这些假设是一种更好的技术。
  3. 断言是一个条件表达式,应该一定总是真,如果它失败,表示程序员犯了错误。实际上,程序最后的成品往往将断言统统删除。

范例

重构前

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

重构后

getExpenseLimit() {
  Assert.isTrue(_expenseLimit !== NULL_EXPENSE || _primaryProject !== null) 
  return (_expenseLimit !== NULL_EXPENSE) ? 
          _expenseLimit :
          _primaryProject.getMemberExpenseLimit()
}

相关文章

  • 简化条件表达式

    0. 本章内容导图 本章提供的重构手法专门用来简化复杂的条件逻辑。 1. 重构手法 1.1 分解条件表达式 概要:...

  • 《重构》- 简化条件表达式

    一. Decompose Conditional(分解条件表达式) 介绍 场景你有一个复杂的条件(if-then-...

  • 重构——简化条件表达式

    1 Decompose Conditional(分解条件表达式) 从复杂表达式if-then-else三个段落中分...

  • 重构-简化条件表达式

    分解条件语句复杂的条件判断抽取为方法 重组条件语句可使用 ||= ,显式返回等替换条件语句 合并条件表达式 合并重...

  • 代码重构专题(转载)

    代码重构(一):函数重构规则代码重构(二):类重构规则代码重构(三):数据重构规则代码重构(四):条件表达式重构规...

  • 第九章 简化条件表达式

    简化条件表达式 9.1 Decompose Conditional (分解条件表达式) 你有一个复杂的条件表达式语...

  • 《重构》学习笔记(07)-- 简化条件表达式

    条件逻辑有可能十分复杂,复杂的条件逻辑可能让复杂度快速上升,并有可能导致代码难以理解。因此,需要一些手段,来简化它...

  • 004-简化条件表达式

    简化条件表达式 1. Decompose Conditional(分解条件表达式) Q:你有一个复杂的条件语句。 ...

  • 简化条件表达式

    我们在编写代码的过程中,有时会因为复杂的业务,导致我们编写的代码圈复杂度过大,if...then...else 过...

  • 重构(八)重构名录-简化条件逻辑

    分解条件表达式Decompose Conditional Expression 动机:复杂的条件逻辑导致复杂度的上...

网友评论

      本文标题:《重构》- 简化条件表达式

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