I have two functions that process similar, but different data. Because of this, there are some variables that are used between both, and some that aren't.
Which of these would be better practice?
Declaring variables in the function that deciding function and passing them as arguments:
Private Sub ProcessData(ByVal x)
Dim a = 1, b = "a", c = new SomeObject(x)
If condition Then
ProcessDataA(x, a, b, c)
Else
ProcessDataB(x, a, b, c)
End If
End Sub
Private Sub ProcessDataA(ByVal x, ByVal a, ByVal b, ByVal c)
' code
End Sub
Private Sub ProcessDataB(ByVal x, ByVal a, ByVal b, ByVal c)
' code
End Sub
or not passing arguments and just instantiating the variables twice?:
Private Sub ProcessData(ByVal x)
If condition Then
ProcessDataA(x)
Else
ProcessDataB(x)
End If
End Sub
Private Sub ProcessDataA(ByVal x)
Dim a = 1, b = "a", c = new SomeObject(x)
' code
End Sub
Private Sub ProcessDataB(ByVal x)
Dim a = 1, b = "a", c = new SomeObject(x)
' code
End Sub
On one hand, the first method prevents code duplication, but I'm not sure how this is treated by compilers/interpreters or if this method has some overhead I'm not aware of.
If the answer varies by language/compiler, I'm specifically curious in the case of the .NET framework or VB.NET.
Thank you!
When
a
,b
andc
will always have the same values for eachProcessData
method than stick to the first option. This way you avoid introducing errors in your program for example when one of these variables have to be changed one time and you forget it for one of the two methods.Also, based on your example code,
a
andb
could be defined as constants in your class.Try to avoid copy and paste in general. "Don't repeat yourself"