重構-Moving Features Between Objects

Refactor
(圖片來自: http://sourcemaking.com/)
以下為學習 Moving Features Between Objects 的筆記.

Extract Class

當一個 Class 負責它不該處理的事時,建立一個新的 Class,將不該處理的變數和方法搬移到新的 Class 中.

優點: 符合 OO. 一個類別只專注在一個事物上.

Hide Delegate

建議參考原文圖7.1,類似 Facade Pattern ,客戶端(最上面層次)透過主機端(中間層次)提供的方法來使用 Delegate 物件. 如此,客戶端將不知道到 Delegate 物件的存在以減少關聯性.

/* 若未使用 Hide Delegate ,在 Client 端的程式碼會常出現如下的狀況. */
Server server = new Server();
server.getDelegate().getMethod(); // 火車頭現象.若換物件去實作,此處要修改.
// server.getMethod(); // Hide delegate. 實作物件被隱藏.

優點: Class 的關聯越少,之後的修改所需的變動越少. 變動被主機端(中間層次)隔絕.

Inline Class

剛好跟 Extract Class 相反. 當你覺得 Class A 做的事不太太多時,將 Class B 整合進來然後刪除 Class B.

Introduce Foreign Method

當你想加入新的方法(這方法常常要被用到)到 Server Class 中,但該 Server Class 不允許修改(ex: Date, String)時. 此時在 Client Class 加上一個以 Server Class 為參數的方法達成目的.

若你發現你產生了多個 Foreign Method ,請改用 Introduce Local Extension .

Foreign Method 其實算是以能先編碼為導向的,最好的方法還是想辦法修改 Server Class ,將合適的方法放到合適的地方.

優點: 可重覆使用原本 Class 未提供的功能.

Introduce Local Extension

當你想加入新的方法(這方法常常要被用到)到 Server Class 中,但該 Server Class 不允許修改(ex: Date, String)時. 利用 繼承/Wrapper 產生新的 Class 來加入新的方法.

最好是只加入新的方法,而不要覆蓋原本的方法(容易造成混淆).

優點: 在不修改原 Class 下,擴充新的能力.

Move Field

Class A 的成員變數被 Class B 用的次數多於 Class A ,將此成員變數移至 Class B .

Move Method

Class A 的方法被 Class B 用的次數多於 Class A ,在 Class B 中建立相同的方法,然後將 Class A 中的方法移除 或 Delegate 至 Class B .

Moving Features Between Objects

Page not Found

Remove Middle Man

剛好跟 Hide Delegate 相反. 當 Server Class 需要提供太多方法讓 Client Class 去使用 Delegate Class ,何不直接讓 Client Class 直接去存取 Delegate Class .

0 則回應: