提取方法是最常用的重構之一。當一個方法看起來太長或者方法中一些代碼需要注釋才能明白它的目的時,可以考慮把它們提取出來作為一個獨立的方法。如:
void PrintOwing()
{
double outstanding = 0;
//print banner
Console.WriteLine("**********");
Console.WriteLine("***Owes***");
Console.WriteLine("**********");
//Calculate outstanding
foreach(Order o in orders)
{
outstanding += o.Amount;
}
//print details
Console.WriteLine("Name: " + name);
Console.WriteLine("Amount: " + outstanding);
}
通過提取方法,重構後代碼如下
void PrintOwing()
{
PrintBanner();
outstanding = GetOutStanding();
PrintDetails(outstanding);
}
void PrintBanner()
{
Console.WriteLine("**********");
Console.WriteLine("***Owes***");
Console.WriteLine("**********");
}
void PrintDetails(int outstanding)
{
Console.WriteLine("Name: " + name);
Console.WriteLine("Amount: " + outstanding);
}
int GetOutStanding()
{
double result = 0;
foreach(Order o in orders)
{
result += o.Amount;
}
return result;
}
經過重構後,代碼看上去清爽多了。提取方法還可以提高代碼的重用性,提高代碼的模塊化程度。