• 推荐
  • 评论
  • 收藏

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

2022-12-02    8993次浏览

Replace Method with Method Object

概述

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

动机(Motivation)

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

示例

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

改为

01 private int importantValue1;
02 private int importantValue2;
03 private int importantValue3;
04  
05 public int Gamma(int inputValue, int quantity, int yearToDate)
06 {
07     importantValue1 = inputValue * quantity + DateTime.Now.Minute;
08     importantValue2 = inputValue * yearToDate + 100;
09     ImportantThing(yearToDate);
10     importantValue3 = importantValue2 * 7;
11     return importantValue3 - 2 * importantValue1;
12 }
13  
14 private void ImportantThing(int yearToDate)
15 {
16     if ((yearToDate - importantValue1) > 100)
17         importantValue2 -= 20;
18 }

Substitute Algorithm(替换你的算法)

概述

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

动机(Motivation)

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

示例

01 public string FoundPerson(string[] people)
02 {
03     for (int i = 0; i < people.Length; i++)
04     {
05         if (people[i].Equals("Don"))
06         {
07             return "Don";
08         }
09         if (people[i].Equals("John"))
10         {
11             return "John";
12         }
13         if (people[i].Equals("Kent"))
14         {
15             return "Kent";
16         }
17     }
18     return "";
19 }

改为

01 public string FoundPerson(string[] people)
02 {
03     List<string> candidates = new List<string>() { "Don""John""Kent" };
04     for (int i = 0; i < people.Length; i++)
05     {
06         if (candidates.Contains(people[i]))
07             return people[i];
08     }
09     return "";
10 }

总结

小型函数优美动人,用较清晰方式取代复杂方式,易于阅读

原文地址:https://www.cnblogs.com/Leo_wl/p/2054856.html