2012-05-18 58 views
0

這是一個關於在.NET面向對象和具體重載函數(或任何其他的框架或語言)的一般問題。我正在查看有很多重複代碼的應用程序。例如,看看以下功能:複製碼和方法重載/重寫

Public Function Test(ByVal Test1 As String) 

//code that is specifically relevant to Test1 variable 

End Function 

Public Function Test (ByVal Test1 As String, ByVal Test2 As String) 
    //code that is specifically relevant to Test1 variable 
    //code that is specifically relevant to Test2 variable 
End Function 

我的認爲最好的初步實踐將是把://代碼,在一個單獨的函數變量的Test1特別相關,因爲它是常見的兩種功能。是這樣嗎?我一直認爲重複代碼是一個非常糟糕的主意。

回答

2

這是不是更好:

Public Function Test(ByVal Test1 As String) 
    //code that is specifically relevant to Test1 variable 
End Function 

Public Function Test (ByVal Test1 As String, ByVal Test2 As String) 
    Test(Test1) 
    //code that is specifically relevant to Test2 variable 
End Function 

超載理想的應該是有關添加aditional的功能,原有的功能,但保留它的原來的行爲,如果你在你的代碼中的其他地方使用它。

+0

感謝您擊中頭部的指甲。答案的關鍵是:Test(Test1),即原始代碼被重用+1。謝謝。 – w0051977

1

通常情況下,我會做這樣的事情,如果可能的話:

Public Function Test(ByVal Test1 As String) 
    Test(Test1, Nothing) 
End Function 

Public Function Test (ByVal Test1 As String, ByVal Test2 As String) 
    ' code that is specifically relevant to Test1 variable 
    If Test2 IsNot Nothing Then 
     ' code that is specifically relevant to Test2 variable 
    End If 
End Function 
+0

感謝您的回答。我同意你的說法+1。我更喜歡Shiin Zu的答案,因爲你將「Nothing」傳遞給你的函數。 – w0051977

+0

謝謝。這兩種方式都是很好的建議,但這取決於哪種情況是合理的。在現實生活中,我會說在實際情況下,祖因的回答方式是沒有意義的,因爲第二個論證影響邏輯中的某些事情,而這些事情在後來不容易做到。實際上,最常見的情況可能是第一個重載不是將Nothing傳遞給第二個參數,而是傳遞一些默認值。 –