范例(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;
}
為了把這個函數變成一個函數對象(method object),我首先需要聲明一個新class。在此新class中我應該提供一個final值域用以保存原先對象(源對象):對于函數的每一個參數和每一個臨時變量,也以一個個值域逐一保存。
class Gamma...
private final Account _account;
private int inputVal;
private int quantity;
private int yearToDate;
private int importantValue1;
private int importantValue2;
private int importantValue3;
接下來,加入一個構造函數:
Gamma (Account source, int inputValArg, int quantityArg, int yearToDateArg) {
_account = source;
inputVal = inputValArg;
quantity = quantityArg;
yearToDate = yearToDateArg;
}
現在可以把原來的函數搬到compute()了。函數中任何調用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;
}
然后,我修改舊函數,讓它將它的工作轉發給剛完成的這個函數對象(method object):
int gamma(int inputVal, int quantity, int yearToDate) {
return new Gamma(this, inputVal, quantity, yearToDate).compute();
}
這就是本項重構的基本原則。它帶來的好處是:現在我可以輕松地對compute()函數采取Extract Method(110),不必擔心引數(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;
}