# 重构手法之重新组织函数【1】

1、Extract Method（提炼函数）

2、Inline Method（内联函数）

3、Inline Temp（内联临时变量）

# 1 Extract Method（提炼函数）

## 动机

• 函数粒度小，被复用的机会大
• 使高层函数读起来像注释
• 函数都是细粒度，更易被复写

## 范例

    public class Receipt
{
private List<decimal> Discounts { get; set; }
private List<decimal> ItemTotals { get; set; }

public decimal CalculateGrandTotal()
{
decimal subTotal = 0m;
//计算subTotal 的总和
foreach (decimal itemTotal in ItemTotals)
{
subTotal += itemTotal;
}
//subTotal 要循环减去discount，也就是计算Discount
if (Discounts.Count > 0)
{
foreach (decimal discount in Discounts)
{
subTotal -= discount;
}
}
//计算Tax
decimal tax = subTotal * 0.065m;
subTotal += tax;
return subTotal;
}

}

重构后代码如下：

 public class Receipt
{
private List<decimal> Discounts { get; set; }
private List<decimal> ItemTotals { get; set; }

public decimal CalculateGrandTotal()
{
decimal subTotal = CalculateSubTotal();

subTotal = CalculateDiscounts(subTotal);

subTotal = CalculateTax(subTotal);

return subTotal;
}
//计算subTotal 的总和
private decimal CalculateSubTotal()
{
decimal subTotal = 0m;
foreach (decimal itemTotal in ItemTotals)
{
subTotal += itemTotal;
}
return subTotal;
}
//计算折扣
private decimal CalculateDiscounts(decimal subTotal)
{
if (Discounts.Count > 0)
{
foreach (decimal discount in Discounts)
{
subTotal -= discount;
}
}
return subTotal;
}
//计算Tax
private decimal CalculateTax(decimal subTotal)
{
decimal tax = subTotal * 0.065m;
subTotal += tax;
return subTotal;
}

}

# 2 Inline Method（内联函数）

## 范例

int GetRating()
{
return MoreThanFiveLateDeliveries() ? 2 : 1;
}

bool MoreThanFiveLateDeliveries()
{
return _numberOfLateDeliveries > 5;
}

int GetRating()
{
return _numberOfLateDeliveries > 5 ? 2 : 1;
}

# 3 Inline Temp（内联临时变量）

## 范例

bool GetBasePrice()
{
double basePrice = anOrder.GetBasePrice();
return basePrice > 1000;
}

重构后代码如下：

bool GetBasePrice()
{
return anOrder.GetBasePrice() > 1000;
}

## 小结

To Be Continued...

posted @ 2017-11-17 07:54  NaYoung  阅读(1263)  评论(0编辑  收藏