有时,看到类似这样的C#语句:
1: private static bool TraditionalVerify(int number)
2: {
3: if ((number > 0) && (number >= 10) && (number % 2 > 0) && (number * 2 > 100))
4: {
5: return true;
6: }
7: return false;
8: }
这里只有四个条件,假设这里有超过四个或更多时,那时代码转行时可读性就更差了。我们可以将上面的代码改成:
1: /// <summary>
2: /// Demo for use Func combine conditions
3: /// </summary>
4: /// <param name="number">need verify number</param>
5: /// <returns>true</returns>
6: /// <seealso cref="http://msdn.microsoft.com/en-us/library/kdxe4x4w.aspx"/>
7: /// <remarks>author Petter Liu http://wintersun.cnblogs.com</remarks>
8: private static bool UseFunc(int number)
9: {
10: var conditionlist = new List<Func<bool>>()
11: {
12: () => number > 0,
13: () => number >= 10,
14: () => number % 2 > 0,
15: () => number * 2 > 100
16: };
17:
18: return conditionlist.TrueForAll(foo => foo.Invoke());
19: }
注意粗体部分的代码,这样看上去更容易阅读。你可增多更多的条件判读语句。实际情况下,还可以考虑Strategies来重构代码。
希望对您开发有帮助!