### Replace Method with Method Object(以函數對象取代函數)
你有一個大型函數,其中對局部變量的使用,使你無法釆用 Extract Method。
將這個函數放進一個單獨對象中,如此一來局部變量就成了對象內的值域(field) 然后你可以在同一個對象中將這個大型函數分解為數個小型函數。
~~~
class Order...
double price() {
double primaryBasePrice;
double secondaryBasePrice;
double tertiaryBasePrice;
// long computation;
...
}
~~~

**動機(Motivation)**
我在本書中不斷向讀者強調小型函數的優美動人。只要將相對獨立的代碼從大型函數中提煉出來,就可以大大提高代碼的可讀性。
但是,局部變量的存在會增加函數分解難度。如果一個函數之中局部變量泛濫成災, 那么想分解這個函數是非常困難的。Replace Temp with Query 可以助你減輕這一負擔,但有時候你會發現根本無法拆解一個需要拆解的函數。這種情況下,你應該把手深深地伸入你的工具箱(好酒沉甕底呢),祭出函數對象(method object )[Beck]這件法寶。
Replace Method with Method Object 會將所有局部變量都變成函數對象(method object)的值域(field)。然后你就可以對這個新對象使用 Extract Method 創造出新函數,從而將原本的大型函數拆解變短。
**作法(Mechanics)**
我厚著臉皮從Kent Beck [Beck]那里偷來了下列作法:
- 建立一個新class,根據「待被處理之函數」的用途,為這個class命名。
- 在新class中建立一個final值域,用以保存原先大型函數所駐對象。我們將這個值域稱為「源對象」。同時,針對原(舊)函數的每個臨時變量和每個參 數,在新中建立一個個對應的值域保存之。
- 在新class中建立一個構造函數(constructor),接收源對象及原函數的所有參數作為參數。
- 在新class中建立一個compute()函數。
- 將原(舊)函數的代碼拷貝到compute()函數中。如果需要調用源對象的任何函數,請以「源對象」值域調用。
- 編譯。
- 將舊函數的函數本體替換為這樣一條語句:「創建上述新的一個新對象, 而后調用其中的compute()函數」。
現在進行到很有趣的部分了。由于所有局部變量現在都成了值域,所以你可以任意分解這個大型函數,不必傳遞任何參數。
**范例(Example)**
如果要給這一重構手法找個合適例子,需要很長的篇幅。所以我以一個不需要長篇幅(那也就是說可能不十分完美)的例子展示這項重構。請不要問這個函數的邏輯是什么,這完全是我且戰且走的產品。
~~~
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 () {
importantValue1 = (inputVal * quantity) + _account.delta();
importantValue2 = (inputVal * yearToDate) + 100;
if ((yearToDate - importantValue1) > 100)
importantValue2 -= 20;
int importantValue3 = importantValue2 * 7;
// and so on.
return importantValue3 - 2 * importantValue1;
}
~~~
然后,我修改舊函數,讓它將它的工作轉發〔委托,delegate)給剛完成的這個函 數對象(method object):
~~~
int gamma (int inputVal, int quantity, int yearToDate) {
return new Gamma(this, inputVal, quantity, yearToDate).compute();
}
~~~
這就是本項重構的基本原則。它帶來的好處是:現在我可以輕松地對compute()函數采取 Extract Method,不必擔心引數(argument)傳遞。
~~~
int compute () {
importantValue1 = (inputVal * quantity) + _account.delta();
importantValue2 = (inputVal * yearToDate) + 100;
importantThing();
int importantValue3 = importantValue2 * 7;
// and so on.
return importantValue3 - 2 * importantValue1;
}
void importantThing() {
if ((yearToDate - importantValue1) > 100)
importantValue2 -= 20;
}
~~~
- 譯序 by 侯捷
- 譯序 by 熊節
- 序言
- 前言
- 章節一 重構,第一個案例
- 起點
- 重構的第一步
- 分解并重組statement()
- 運用多態(Polymorphism)取代與價格相關的條件邏輯
- 結語
- 章節二 重構原則
- 何謂重構
- 為何重構
- 「重構」助你找到臭蟲(bugs)
- 何時重構
- 怎么對經理說?
- 重構的難題
- 重構與設計
- 重構與性能(Performance)
- 重構起源何處?
- 章節三 代碼的壞味道
- Duplicated Code(重復的代碼)
- Long Method(過長函數)
- Large Class(過大類)
- Long Parameter List(過長參數列)
- Divergent Change(發散式變化)
- Shotgun Surgery(散彈式修改)
- Feature Envy(依戀情結)
- Data Clumps(數據泥團)
- Primitive Obsession(基本型別偏執)
- Switch Statements(switch驚悚現身)
- Parallel Inheritance Hierarchies(平行繼承體系)
- Lazy Class(冗贅類)
- Speculative Generality(夸夸其談未來性)
- Temporary Field(令人迷惑的暫時值域)
- Message Chains(過度耦合的消息鏈)
- Middle Man(中間轉手人)
- Inappropriate Intimacy(狎昵關系)
- Alternative Classes with Different Interfaces(異曲同工的類)
- Incomplete Library Class(不完美的程序庫類)
- Data Class(純稚的數據類)
- Refused Bequest(被拒絕的遺贈)
- Comments(過多的注釋)
- 章節四 構筑測試體系
- 自我測試代碼的價值
- JUnit測試框架
- 添加更多測試
- 章節五 重構名錄
- 重構的記錄格式
- 尋找引用點
- 這些重構準則有多成熟
- 章節六 重新組織你的函數
- Extract Method(提煉函數)
- Inline Method(將函數內聯化)
- Inline Temp(將臨時變量內聯化)
- Replace Temp with Query(以查詢取代臨時變量)
- Introduce Explaining Variable(引入解釋性變量)
- Split Temporary Variable(剖解臨時變量)
- Remove Assignments to Parameters(移除對參數的賦值動作)
- Replace Method with Method Object(以函數對象取代函數)
- Substitute Algorithm(替換你的算法)
- 章節七 在對象之間搬移特性
- Move Method(搬移函數)
- Move Field(搬移值域)
- Extract Class(提煉類)
- Inline Class(將類內聯化)
- Hide Delegate(隱藏「委托關系」)
- Remove Middle Man(移除中間人)
- Introduce Foreign Method(引入外加函數)
- Introduce Local Extension(引入本地擴展)
- 章節八 重新組織數據
- Self Encapsulate Field(自封裝值域)
- Replace Data Value with Object(以對象取代數據值)
- Change Value to Reference(將實值對象改為引用對象)
- Replace Array with Object(以對象取代數組)
- Replace Array with Object(以對象取代數組)
- Duplicate Observed Data(復制「被監視數據」)
- Change Unidirectional Association to Bidirectional(將單向關聯改為雙向)
- Change Bidirectional Association to Unidirectional(將雙向關聯改為單向)
- Replace Magic Number with Symbolic Constant(以符號常量/字面常量取代魔法數)
- Encapsulate Field(封裝值域)
- Encapsulate Collection(封裝群集)
- Replace Record with Data Class(以數據類取代記錄)
- Replace Type Code with Class(以類取代型別碼)
- Replace Type Code with Subclasses(以子類取代型別碼)
- Replace Type Code with State/Strategy(以State/strategy 取代型別碼)
- Replace Subclass with Fields(以值域取代子類)
- 章節九 簡化條件表達式
- Decompose Conditional(分解條件式)
- Consolidate Conditional Expression(合并條件式)
- Consolidate Duplicate Conditional Fragments(合并重復的條件片段)
- Remove Control Flag(移除控制標記)
- Replace Nested Conditional with Guard Clauses(以衛語句取代嵌套條件式)
- Replace Conditional with Polymorphism(以多態取代條件式)
- Introduce Null Object(引入Null 對象)
- Introduce Assertion(引入斷言)
- 章節十一 處理概括關系
- Pull Up Field(值域上移)
- Pull Up Method(函數上移)
- Pull Up Constructor Body(構造函數本體上移)
- Push Down Method(函數下移)
- Push Down Field(值域下移)
- Extract Subclass(提煉子類)
- Extract Superclass(提煉超類)
- Extract Interface(提煉接口)
- Collapse Hierarchy(折疊繼承關系)
- Form Template Method(塑造模板函數)
- Replace Inheritance with Delegation(以委托取代繼承)
- Replace Delegation with Inheritance(以繼承取代委托)
- 章節十二 大型重構
- 這場游戲的本質
- Tease Apart Inheritance(梳理并分解繼承體系)
- Convert Procedural Design to Objects(將過程化設計轉化為對象設計)
- Separate Domain from Presentation(將領域和表述/顯示分離)
- Extract Hierarchy(提煉繼承體系)
- 章節十三 重構,復用與現實
- 現實的檢驗
- 為什么開發者不愿意重構他們的程序?
- 現實的檢驗(再論)
- 重構的資源和參考資料
- 從重構聯想到軟件復用和技術傳播
- 結語
- 參考文獻
- 章節十四 重構工具
- 使用工具進行重構
- 重構工具的技術標準(Technical Criteria )
- 重構工具的實用標準(Practical Criteria )
- 小結
- 章節十五 集成
- 參考書目