以函数对象取代函数
使用场景: 你有一个大型函数,其中对局部变量的使用使你无法采用Extract Method.
解决方法:将这个函数放进一个单独的对象中,如此一来局部变量就变成了对象内字段,然后可以在同一个对象将这个大型函数分解为多个小型函数。
代码解释:
package 第六章;
public class Account {
//重构前:较为大型的函数体
int gamma(int inputVal, int quantity, int yearToDate) {
int importantValue1 = (inputVal * quantity) + delta();
int importantValue2 = (inputVal * yearToDate) + 100;
if ((yearToDate - importantValue1) > 100)
importantValue2 -= 20;
int importantValue3 = importantValue2 * 7;
return importantValue3 - importantValue1 * 2;
}
int delta() {
return 1;
}
//重构后:提取Gamma对象,并将计算需要的变量仍以参数的方式传递过去,将计算的过程提取函数进行计算
int gamma(int inputVal,int quantity,int yearToDate){
return new Gamma(this,inputVal,quantity,yearToDate).compute();
}
class Gamma {
private final Account account;
private int inputVal;
private int quantity;
private int yearToDate;
private int importantValue1;
private int importantValue2;
private int importantValue3;
public Gamma(Account source, int inputVal, int quantity, int yearToDate) {
super();
this.account = source;
this.inputVal = inputVal;
this.quantity = quantity;
this.yearToDate = yearToDate;
this.importantValue1 = importantValue1;
this.importantValue2 = importantValue2;
this.importantValue3 = importantValue3;
}
int compute() {
importantValue1 = (inputVal * quantity) + account.delta();
importantValue2 = (inputVal * yearToDate) + 100;
importantValue3 = importantValue2 * 7;
return importantValue3 - importantValue1 * 2;
}
//可以轻松使用Extract Method()的方式提取函数,不必担心传递参数的问题
void importantThing(){
if ((yearToDate - importantValue1) > 100)
importantValue2 -= 20;
}
}
public static void main(String[] args) {
Account a = new Account();
int result = a.gamma(100, 100, 100);
System.out.println("result: "+result);
}
}