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!

3

There are 3 answers

0
Andreas Adler On BEST ANSWER

When a, b and c will always have the same values for each ProcessData 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 and b could be defined as constants in your class.

Try to avoid copy and paste in general. "Don't repeat yourself"

0
Lauren On

If the variable aren't actually carrying any useful values, then in my opionion, it is better to keep them local to the methods. Could a passed in, unexpected value possible lead to an error ?

0
Markus On

It depends on how "expensive" the instantiation of the variables is. If the construction of the objects is expensive in terms of performance or resources, it is of course better to create them once and pass them to the methods.
If you want to keep your methods independent from each other and the construction is not expensive, creating them locally is a good and clean way.
As both ProcessDataA and ProcessDataB are private, you can easily change the approach later on.