If x is equal to 1 then we need the SqlDataReader from GetDataReader1 method. Otherwise, we need SqlDataReader from GetDataReader2. That is the only difference. Other than that, all the code needed (where it says do stuff here) is going to be duplicated. How can I make this more elegant so I don’t have to repeat all the logic within both using statements?
Update: In simplifying the code for this post, I missed an additional factor. GetDataReader1 takes 2 parameters and GetDataReader2 takes 3 parameters. If I create one GetDataReader function, and move the If statement there, will I be forced to pass in the extra parameter that is currently not needed for the GetDataReader1 method?
Dim value1, value2, value3 As String
If x = 1 Then
Using myDataReader As SqlDataReader = GetDataReader1(value1, value2)
myDataReader.Read()
If myDataReader.HasRows Then
'do stuff here
End If
End Using
Else
Using myDataReader As SqlDataReader = GetDataReader2(value1, value2, value3)
myDataReader.Read()
If myDataReader.HasRows Then
'do stuff here
End If
End Using
End If
Pass in
xtoGetDataReaderand let it determine what to return.This pushes the
IfintoGetDataReaderwhere your shouldn’t have much duplication.Update – following update on the question.
You can still use the same mechanism – pushing the decision to a method – you simply need to pass in all the parameters that may be needed in addition to
x: