Sean's Note: [讀書筆記] Refactoring - Chapter7 - 8

2015年4月7日 星期二

[讀書筆記] Refactoring - Chapter7 - 8

Chapter 7. Moving Features Between Objects

Move Method
如果一個在 Class A 的函式 M 用到了更多 Class B  的變數或方法,那是不是可以考慮將函式 M 移至 Class B?

Move Field
與 Move Method 同理。

Extract Class
檢視一個 Class 是否可以利用 Move Method 和 Move Field 在拆分為多個 Class。

Inline Class
與 Extract Class 反之。

Hide Delegate
Client 想取得 Class A 的 delegate Class B 的某資訊時,不需將 Class B 完全揭露給 Client,可以在 Class A 新增一個函式將資訊回傳即可。

Remove Middle Man
與 Hide Delegate 反之,如果上述新增的方法太多,就直接揭露吧。

Introduce Foreign Method
當在使用一個無法更動的 Server Class 時,考慮在 Client 裡新增一個以 Server Class 為參數的函式吧。

Introduce Local Extension
當有太多的 Foreign Method 時可考慮 subclass 或 wrapper Server Class。Wrapper 比較麻煩的是得寫出原 Server Class 所提供的函式。

Chapter 8. Organizing Data

Self Encapsulate Field
對於 Class 自身的成員變數,可不可以直接存取,還是要透過 accessors,有兩方學派的人馬各持己見。如果 Class 本身有可能被 subclass,且 Subclass 對於成員變數有不同的定義或計算方法,accessors 仍然是解決的方法,此外,直接存取也無妨。

Replace Data Value with Object
當資料可能有其他子資料或行為時,考慮把它寫成物件吧。

Change Value to Reference
EX: 把原本 Order 與 Customer 的組合關係(Composition),改成一般的結合關係(Associations),同名的 Custom 應該只有一個 Object。

Change Reference to Value
EX: 把原本 Company 與 Currency 的結合關係(Associations),改成組合關係(Composition)。我們不在乎兩個 "USD" Currency 是不是同一個 Object,只要知道他們相等就好。

Replace Array with Object
Array 應該是拿來放有相同型態的物件集合,如果要放不一樣的,不如使用物件吧。

Duplicate Observed Data 
Observer pattern 

Change Unidirectional Association to Bidirectional 


Change Bidirectional  Association to Unidirectional


Replace Magic Number with Symbolic Constant
這還蠻常用的,提高可讀性。

Encapsulate Field
封裝成員變數,public to private + accessors。

Encapsulate Collection
add + remove - setter method。

Replace Record with Data Class
封裝成員變數,public to private + accessors

Replace Type Code with Class
實用。

Replace Type Code with Subclass
如果 type code 影響了 class 的行為,考慮繼承吧。

Replace Type Code with State/Strategy
詳見範例。

Replace Subclass with Fields 
用 Factory Method 來取代 constructor,詳見範例。

沒有留言:

張貼留言