《重构:改善既有代码的设计》中提到过很多重构方法,关于重新组织函数的方法有9种。本文介绍:
以查询取代临时变量 replace temp with query
- 名称:以查询取代临时变量 replace temp with query
- 概要:以一个临时变量保存某一个表达式的运算结果。将这个表达式提炼到一个独立函数中,将这个临时变量的所有引用点替换为对新函数的调用。此后,这个新函数就可以被其他函数使用。
- 动机:临时变量会导致函数变的更长。而新函数可以被其他函数复用
- 做法:
- 找出只被赋值一次的临时变量。如果临时变量被赋值超过一次,先使用split temporary variable 将它分割成多个变量。
- 将对该临时变量赋值的语句的等号右侧部分提炼到一个独立函数中。首先将函数声明为private,将来修改叶可以。
- 编译,测试
- 在该临时变量身上实施 inline temp
- 代码演示:
修改之前的代码:
double BasePrice = m_Quantity * m_ItemPrice;
double DiscountFactor = 0;
if (BasePrice > 100)
{
BasePrice = 0.95;
}
else
{
BasePrice = 0.98;
}
return DiscountFactor * BasePrice;
修改之后的代码:
double RefactorMethod::GetPrice()
{
return GetBasePrice() * GetPrice();
}
double RefactorMethod::GetBasePrice()
{
return m_Quantity * m_ItemPrice;
}
double RefactorMethod::DiscountFactor()
{
if (GetBasePrice() > 100)
{
return 0.95;
}
else
{
return 0.98;
}
}