VB.NETで2つのオーバーロードされた関数を記述したいと思います。
2つの関数のロジックのほとんどは同じであるため、2つのオーバーロードに対して関数全体を複製するだけでは不十分です。
これは、オーバーロードされた各関数に、次のようなオプションのパラメーターを使用して別の関数(コアロジックを含む)を呼び出させることで実現できます。
Public Overloads Function GetLocationDetails(ByVal countryId As Integer) As LocationInfo
Return _GetLocationDetails(countryId)
End Function
Public Overloads Function GetLocationDetails(ByVal countryId As Integer, ByVal stateId As Integer) As LocationInfo
Return _GetLocationDetails(countryId, stateId)
End Function
' This is the function providing the core logic for the two overloaded functions
Private Function _GetLocationDetails(ByVal countryId As Integer, Optional ByVal stateId As Integer = 0) As LocationInfo
Dim returnVal As New LocationInfo
Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("myConnectionString").ConnectionString)
Using cmd As SqlCommand = con.CreateCommand
cmd.CommandText = "SELECT name, population FROM locations WHERE countryId = @countryId"
cmd.Parameters.Add(New SqlParameter("@countryId", countryId))
' If there is a stateId, this function was called by the overloaded function that has a stateId parameter, so add that to the query
If stateId <> 0 Then
cmd.CommandText &= " AND stateId = @stateId"
cmd.Parameters.Add(New SqlParameter("@stateId", stateId))
End If
con.Open()
Using dr As SqlDataReader = cmd.ExecuteReader
If dr.Read Then
returnVal.Name = dr("name")
returnVal.Population = dr("population")
End If
End Using
End Using
End Using
Return returnVal
End Function
Public Class LocationInfo
Public Name As String
Public Population As Integer
End Class
しかし、オプションのパラメーターを使用することはあまり洗練されていないようであり、そもそも関数をオーバーロードするという目的全体を否定しているようです。
もっと良い方法はありますか?