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 变量特别相关的代码放在一个单独的函数中,因为它在两个函数中都很常见。是这样吗?我一直认为重复代码是一个非常糟糕的主意。

4

2 回答 2

3

这不是更好:

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 

理想情况下,重载应该是向原始函数添加附加功能,但保留它的原始行为,以防您在代码中的其他地方使用它。

于 2012-05-18T20:57:38.103 回答
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
于 2012-05-18T20:50:43.507 回答