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

Replace Method with Method Object

概述

将这个函数放进一个单独对象中,如此一来局部变量就成了对象内的值域(field),然后你可以在同一个对象中将这个大型函数分解为数个小型函数.

动机(Motivation)

小型函数优美动人,只要将相对独立的代码从大型函数中提炼出来,就可以大在提高代码的可读性.

示例

       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(替换你的算法)

概述

将函数本体(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/springyangwc/p/2054716.html