代码重构(一)-用函数对象代替函数(replace method with method object)
2017-10-11 15:54
603 查看
在程序开发中程序重构是必须也是必不可少的一个部分。在程序开发工程中我们一向不断的腔调小型的函数,小型函数的可读性高。其中函数过长造成函数的可读性差是我们经常遇到的一个问题,因此代码重构就是一项必不可少的一个环节了。但是在重构过程中我们会越到很多的问题,包含函数内部局部变量多,相互之间有引用关系,从而为函数的拆解提供了很大的不便。为了解决这种问题,我们就提出来一个解决的办法用函数对象代替函数(replace method with method object).不多说直接附上案例;、
原函数:
根据函数提炼出对应的函数类:
原函数:
package test; public class Account { public int gamma(int one,int two,int three ){ return new Gamma(this, one, two, three).compute(); } public int delta(){ return 0; } }
根据函数提炼出对应的函数类:
package test; /** * * 重构,以函数对象取代函数 * * @author jhone * */ public class Gamma { private Account _account; private int imp_one; private int imp_two; private int imp_three; private int one; private int two; private int three; // 添加构造函数 public Gamma(Account _account, int imp_one, int imp_two, int imp_three) { this._account = _account; this.imp_one = imp_one; this.imp_two = imp_two; this.imp_three = imp_three; } public int compute(){ imp_one = (one+two) + _account.delta(); imp_two = (one + three) + 100; if ((three - imp_one) > 100) { imp_two -=20; } imp_three = imp_two + 7 ; return imp_three - 2 + imp_one; } }
相关文章推荐
- 重构改善既有代码设计--重构手法08:Replace Method with Method Object (以函数对象取代函数)
- 重构手法08:Replace Method with Method Object (以函数对象取代函数)
- 读书笔记-重构-Replace Method with Method Object(用对象代替方法)
- java重构学习7:以函数对象取代函数(Replace Method with Method Object)
- 重新组织函数--Replace Method with Method Object(以函数对象取代函数)
- Replace Method with Method Object (以函数对象取代函数)
- Replace Method with Method Object(以函数对象取代函数)
- Replace Method with Method Object(以函数对象取代函数)
- 重构改善既有代码设计--重构手法19:Replace Data Value with Object (以对象取代数据值)
- 『重构--改善既有代码的设计』读书笔记----Replace Method with Method Object
- Replace Method with Method Object(以函数对象取代函数)
- 重构手法19:Replace Data Value with Object (以对象取代数据值)
- 步步为营 .NET 代码重构学习笔记 五、分解函数和替换算法(Replace Method And Substitute Algorithm)
- java 代码细节(Replace Method with Method Object)
- 步步为营 .NET 代码重构学习笔记 四、分解函数和替换算法(Replace Method And Substitute Algorithm)
- 重构-代替类型代码几中方式的比较(Replace type code with ...)
- 重构手法22:Replace Array with Object (以对象取代数组)
- 重构手法53:Replace Constructor with Factory Method (以工厂函数取代构造函数)
- 『重构--改善既有代码的设计』读书笔记----Replace Array with Object
- 『重构--改善既有代码的设计』读书笔记----Replace Data Value with Object