重构之重新组织函数(Substitute Algorithm)

概述

将函数本体(method body)替换为另一个算法。

动机(Motivation)

如果你发现做一件事可以有更清晰的方式,就应该以较清晰的方式取代复杂方式。可以把一些复杂的东西分解为较简单的小块,但有时你就是必须壮士断腕,删掉整个算法,代之较简单的算法。

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 "";
}
原文地址:https://www.cnblogs.com/newbee0101/p/11970950.html