假如有個複雜邏輯的演算法, 需要重構成一個函數, 但是這邏輯只會用在一個地方.
假如有個手機遊戲, 根據會員的等級, 所消費的道具(ex: 鑽石)會有各種折扣.
public enum PlayerType
{
None,
Bronze,
Silver,
Gold
}
public class BuyItem
{
public decimal Cost { get; set; }
public string Description { get; set; }
}
我們建立一個假的消費集合:
private static List<BuyItem> GetBuyItems()
{
var result = new List<BuyItem>();
var rand = new Random();
for (int i = 0; i < 10; i++)
{
result.Add(
new BuyItem
{
Cost = rand.Next(i),
Description = "Item #" + (i + 1)
});
}
return result;
}
在主邏輯執行此折扣計算:
static void Main()
{
List<BuyItem> items = GetBuyItems();
decimal total = 0;
foreach (var item in items)
total += item.Cost;
total = ApplyDiscount(total, PlayerType.Silver);
Console.WriteLine($"Total Balance: {total:C}");
decimal ApplyDiscount(decimal total, CustomerType customerType)
{
switch (customerType)
{
case CustomerType.Bronze:
return total * 0.9m;
case CustomerType.Silver:
return total * 0.85m;
case CustomerType.Gold:
return total * 0.8m;
case CustomerType.None:
default:
return total;
}
}
}
從上述看到, ApplyDiscount
是一個local函數, 並不是class等級的method.
ApplyDiscount
這種函數不抽到class等級, 是讓後續維護class時不用花太多時間了解它. 畢竟它只是一個函數(區域)內的一段邏輯.