2010-04-28 73 views
1

我剛剛問了一個關於使用泛型(或多態)來避免重複代碼的問題。我真的很想遵循DRY原則。你會使用Action委託來避免重複的代碼嗎?

所以我只是碰到了下面的代碼...

Sub OutputDataToExcel() 

     OutputLine("Output DataBlocks", 1) 
     OutputDataBlocks() 
     OutputLine("") 

     OutputLine("Output Numbered Inventory", 1) 
     OutputNumberedInventory() 
     OutputLine("") 

     OutputLine("Output Item Summaries", 1) 
     OutputItemSummaries() 
     OutputLine("") 

End Sub 

我應該重寫這段代碼是使用Action委託如下...

Sub OutputDataToExcel() 
    OutputData("Output DataBlocks", New Action(AddressOf OutputDataBlocks)) 
    OutputData("Output Numbered Inventory", New Action(AddressOf OutputNumberedInventory)) 
    OutputData("Output Item Summaries", New Action(AddressOf OutputItemSummaries)) 
End Sub 

Sub OutputData(ByVal outputDescription As String, ByVal outputType As Action) 
    OutputLine(outputDescription, 1) 
    outputType() 
    OutputLine("") 
End Sub 

我意識到這個問題主觀。我只是想知道你如何虔誠地遵循DRY。你會這樣做嗎?

賽斯

回答

4

我見過這個叫做「中間孔」的模式。 「真實世界的函數式編程」一書提到了它。這是一個鏈接。

http://enfranchisedmind.com/blog/posts/the-hole-in-the-middle-pattern/

看到,還有我已經得到了 在Ocaml-使用的模式,我甚至想用它在Perl ,這是我認爲的「洞 在中間」模式。基本想法 是你有兩個幾乎完全相同的代碼 , 除了那個小中間部分 那裏。這個想法是,你將 公用代碼分解成一個單一的 函數,該函數採用函數 指針作爲參數。在共享代碼中間 部分由 到函數指針的呼叫時,以及 兩個地正被 加起來只需調用組合 函數的指針包含該獨特部分的函數 代替。

+1

中間圖案的孔?它也可以稱爲甜甜圈模式嗎? MMMMM ...甜甜圈。 – 2010-04-28 19:26:47

1

我不會說我用它所有的時間,但我已經使用Action委託,以避免重複代碼。我已經使用過的一種場景是將WCF調用(在客戶端代理中)封裝起來以避免使用相同的鍋爐代碼。

private void InvokeAndHandleFaults(
     Action<Data, Context> wcfCall, 
     Data data, 
     Context context) 
    { 
     bool isSuccess = false; 

     try 
     { 
      wcfCall(data, context); 

      if (this.ChannelFactory.State != System.ServiceModel.CommunicationState.Faulted) 
      { 
       this.ChannelFactory.Close(); 
      } 

      isSuccess = true; 
     } 
     catch (FaultException ex) 
     { 
      HandleFault(ex); 
     } 
     finally 
     { 
      if (!isSuccess) 
      { 
       this.ChannelFactory.Abort(); 
      } 
     } 
    } 

就問題中的示例而言,我可能不會使用Action。我絕對不會重構使用Action。主要是因爲實際的邏輯很簡單,所以我沒有看到太多的好處。隨着重複代碼的「複雜性」/大小增加,我更可能使用委託。