步步为营 .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 "" ; } |
总结
小型函数优美动人,用较清晰方式取代复杂方式,易于阅读,
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架