Search code examples
vb.netlanguage-agnosticprogramming-languages

Bad Practice to Pass ByRef and ByVal Parameters In Same Routine?


Is it considered bad practice (VB.NET or any language) to code a function with both ByVal and ByRef parameters as used in my getFile function below?

Function getFile(ByVal channel As Integer, _
                 ByRef Filename As String, _
                 ByRef Filesize As String) As Integer
...
End Function

...
Dim status As Integer
Dim filename As String
Dim filesize As Integer

For channel In 1 To 16
   status = getFile(channel, filename, filesize) 
   ...
Next channel

Solution

  • I usually try to avoid ByRef all together, it often ends up being ugly and confusing. The fact that you're mixing ByVal and ByRef doesn't affect readibility any more than just having all ByRef IMHO.

    For example, if I only need the filename, I'd still need to pass in a filesize variable, which I think makes it a bit uglier. And when reading code it can be easy to miss that a parameter might be changed.

    As Assaf also says in his comment, instead I'd normally try to get around the whole issue by having the method return some kind of structure that can contain all the return data. and if it failed I'd throw an exception rather than return the status (assuming that the status is some kind of error).