2011-11-01 71 views
1

在我們的代碼庫如何重構這些方法以避免重複?

public ActionResult Copy(string id, string targetId) 
      { 
       //lot of similar code 
       Copy(sourcePageRef, destinationPageRef); 
       //lot of similar code 
      } 

public ActionResult Move(string id, string targetId) 
     { 
      //lot of similar code 
      Move(sourcePageRef, destinationPageRef); 
      //lot of similar code 
     } 

的問題是,複製和移動有不同的簽名:

PageRef Copy(PageRef, PageRef) 

void Move(PageRef, PageRef) 

我如何重構這些方法以避免重複? 謝謝

+0

如果您可以放棄複製操作的結果,通常會使用立面模式。使用相同的簽名實現複製和移動你的外觀,然後你可以反射性地或不管你喜歡地稱它們。否則,我首先將通用代碼移動到輔助方法中。 –

回答

7

如果你不需要的Copy的結果,你仍然可以使用Action<string, string>或任何類型是:

public ActionResult Copy(string id, string targetId) 
{ 
    CopyOrMove((x, y) => Copy(x, y)); 
} 

public ActionResult Move(string id, string targetId) 
{ 
    CopyOrMove(id, targetId, (x, y) => Move(x, y)); 
} 

private void CopyOrMove(string id, string targetId, 
         Action<string, string> fileAction) 
{ 
    // lot of similar code 
    fileAction(sourcePageRef, destinationPageRef); 
    // lot of similar code 
} 

這是一個選項。這取決於「很多類似代碼」的確在做什麼,以及第二個塊是否需要第一個塊的結果。例如,如果你可以這樣做:

public ActionResult Copy(string id, string targetId) 
{ 
    string sourcePageRef = PrepareSourceFile(id, targetId); 
    string targetPageRef = PrepareTargetFile(targetId); 
    Copy(sourcePageRef, targetPageRef); 
    CleanUp(sourcePageRef, targetPageRef); 
    return ...; 
} 

public ActionResult Move(string id, string targetId) 
{ 
    string sourcePageRef = PrepareSourceFile(id, targetId); 
    string targetPageRef = PrepareTargetFile(targetId); 
    Move(sourcePageRef, targetPageRef); 
    CleanUp(sourcePageRef, targetPageRef); 
    return ...; 
} 

...那麼這可能比重構委託方式更簡單。

+0

完美解決我的問題!謝謝 – Vimvq1987

0

我不會重構那些方法,但如果可能的話,將這些方法的內容放入單獨的私有函數中,在一種情況下將數據移動到另一份副本中。所以你提供的方法可以使用它。從方法的名稱可以清楚地看到它的作用,不要改變它,因爲它們對於你的類的消費者來說是公開的和可見的。

0

提取這些:

//很多類似的代碼

自己的方法,只是叫他們從你的移動或複製的方法。

0

我看到2種選擇: 選項A)用分解方法,以提取公共代碼,和類從每個重複的方法,該方法的代碼:

Copy(,) { 
    CommonCodeA(); 
    Copy(..); 
    CommonCodeB(); 
    } 

    Move(,) { 
    CommonCodeA(); 
    Move(..); 
    CommonCodeB(); 
    } 

    CommonCodeA() {...} 

    CommonCodeB() {...} 

選項B)使用模板Method重構:把公共代碼在超類方法中,並使該方法爲特定代碼調用抽象方法。然後爲每個重複的方法創建一個子類,實現抽象方法。

class OperationAction { 

     operation() { 
      //lots of code 
      do(,); 
      //lots of code 
     } 
     abstract do(); 
} 

class CopyAction extends OperationAction { 
    do() { 
      Copy(srcref,destref); 
    } 
    Copy(srcref,destref) { ... } 
} 

class MoveAction extends OperationAction { 
    do() { 
      Move(srcref,destref); 
    } 
    Move(srcref,destref) { ... } 
}