您的位置:首页 > 移动开发 > Objective-C

代码重构(一)-用函数对象代替函数(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;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐