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

Replace Method with Method Object

概述

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

动机(Motivation)

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

示例

1
2
3
4
5
6
7
8
9
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;
}

改为

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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)

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

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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 "";
}

改为

1
2
3
4
5
6
7
8
9
10
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 "";
}

总结

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

posted @   spring yang  阅读(2088)  评论(0编辑  收藏  举报
编辑推荐:
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
阅读排行:
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
· 上周热点回顾(2.17-2.23)
点击右上角即可分享
微信分享提示