《重构:改善既有代码的设计》中提到过很多重构方法,关于重新组织函数的方法有9种。本文介绍:
引入解释性变量 introduce explaining value
- 名称:引入解释性变量 introduce explaining value
- 概要:将该复杂表达式(或其中一部分)的结果放进一个临时变量,以此变量名称来解释表达式用途
- 动机:表达式有时候非常复杂且难以阅读,运用变量来解释对应条件子句的意义。另外,在较长算法中,可以运用临时变量来解释每一步运算的意义。
- 做法:
- 将待分解之复杂表达式的一部分运算结果赋值给一个临时变量
- 用临时变量替换表达式
- 编译,测试
- 代码演示:
修改之前的代码:
double RefactorMethod::Price()
{
return m_Quantity * m_ItemPrice -
std::max(0,m_Quantity - 500) * m_ItemPrice * 0.05 +
std::min(m_Quantity * m_ItemPrice * 0.1, 100.0);
}
修改之后的代码:
double RefactorMethod::Price()
{
double QuantityDiscount = std::max(0,m_Quantity - 500) * m_ItemPrice * 0.05;
double Shipping = std::min(m_Quantity * m_ItemPrice * 0.1, 100.0);
return GetBasePrice() - QuantityDiscount + Shipping;
}
继续重构:使用extract method将 QuantityDiscount 和 shipping变成函数。