Spiga

一天一个重构方法(9):替换算法

2009-05-23 07:06:08

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>(people);
	for (int i = 0; i < people.Length; i++)
	{
		if (candidates.Contains(people[i]))
			return people[i];
	}
	return "";
}