范例(Examples)
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;
// and so on.
return importantValue3 -2 * importantValue1;
}
為了把這個(gè)函數(shù)變成一個(gè)函數(shù)對(duì)象(method object),我首先需要聲明一個(gè)新class。在此新class中我應(yīng)該提供一個(gè)final值域用以保存原先對(duì)象(源對(duì)象):對(duì)于函數(shù)的每一個(gè)參數(shù)和每一個(gè)臨時(shí)變量,也以一個(gè)個(gè)值域逐一保存。
class Gamma...
private final Account _account;
private int inputVal;
private int quantity;
private int yearToDate;
private int importantValue1;
private int importantValue2;
private int importantValue3;
接下來,加入一個(gè)構(gòu)造函數(shù):
Gamma (Account source, int inputValArg, int quantityArg, int yearToDateArg) {
_account = source;
inputVal = inputValArg;
quantity = quantityArg;
yearToDate = yearToDateArg;
}
現(xiàn)在可以把原來的函數(shù)搬到compute()了。函數(shù)中任何調(diào)用Account class的地方,我都必須改而使用_account值域:
int compute() {
int importantValue1 = (inputVal * quantity) + _account.delta();
int importantValue2 = (inputVal * yearToDate) + 100;
if((yearToDate - importantValue1) > 100)
importantValue2 -= 20;
int importantValue3 = importantValue2 * 7;
// and so on.
return importantValue3 -2 * importantValue1;
}
然后,我修改舊函數(shù),讓它將它的工作轉(zhuǎn)發(fā)給剛完成的這個(gè)函數(shù)對(duì)象(method object):
int gamma(int inputVal, int quantity, int yearToDate) {
return new Gamma(this, inputVal, quantity, yearToDate).compute();
}
這就是本項(xiàng)重構(gòu)的基本原則。它帶來的好處是:現(xiàn)在我可以輕松地對(duì)compute()函數(shù)采取Extract Method(110),不必?fù)?dān)心引數(shù)(argument)傳遞。
int compute() {
int importantValue1 = (inputVal * quantity) + _account.delta();
int importantValue2 = (inputVal * yearToDate) + 100;
importantThing();
int importantValue3 = importantValue2 * 7;
// and so on.
return importantValue3 -2 * importantValue1;
}
void importantThing() {
if((yearToDate - importantValue1) > 100)
importantValue2 -= 20;
}