# 步步为营 .NET 代码重构学习笔记 五、分解函数和替换算法(Replace Method And Substitute Algorithm)

Replace Method with Method Object

       public int Gamma(int inputValue, int quantity, int yearToDate)
{
int importantValue1 = inputValue * quantity + DateTime.Now.Minute;
int importantValue2 = inputValue * yearToDate + 100;
if ((yearToDate - importantValue1) > 100)
importantValue2 -= 20;
int importantValue3 = importantValue2 * 7;
return importantValue3 - 2 * importantValue1;
}

        private int importantValue1;
private int importantValue2;
private int importantValue3;

public int Gamma(int inputValue, int quantity, int yearToDate)
{
importantValue1 = inputValue * quantity + DateTime.Now.Minute;
importantValue2 = inputValue * yearToDate + 100;
ImportantThing(yearToDate);
importantValue3 = importantValue2 * 7;
return importantValue3 - 2 * importantValue1;
}

private void ImportantThing(int yearToDate)
{
if ((yearToDate - importantValue1) > 100)
importantValue2 -= 20;
}

Substitute Algorithm（替换你的算法）

        public string FoundPerson(string[] people)
{
for (int i = 0; i < people.Length; i++)
{
if (people[i].Equals("Don"))
{
return "Don";
}
if (people[i].Equals("John"))
{
return "John";
}
if (people[i].Equals("Kent"))
{
return "Kent";
}
}
return "";
}

        public string FoundPerson(string[] people)
{
List<string> candidates = new List<string>() { "Don", "John", "Kent" };
for (int i = 0; i < people.Length; i++)
{
if (candidates.Contains(people[i]))
return people[i];
}
return "";
}

posted @ 2011-05-23 20:42  spring yang  阅读(2065)  评论(0编辑  收藏  举报