Visual Basic

Functions are returning some data and an indication of the function's success

It is quite common to use the return value of a function to return True, False, or perhaps an error code. The actual data value is returned as a parameter by reference. For example, consider this code fragment:

bRet = GetFileVersion(ByRef nVersion, filename)

Here the version of filename is returned by reference, provided the file was found correctly. If the file was not found, the function will return False and nVersion will not be accurate. You have a couple of alternatives.

  • Raise errors. This has always been the Visual Basic way. (For example, Visual Basic's own Open works in this way.)
  • Return a Variant and use the CVErr function to create a Variant of subtype vbError holding the error condition. The caller can then use IsError as follows:
    nVersion = GetFileVersion(filename)
      If IsError(nVersion) Then
          ' nVersion is unreliable, take some action...
      Else
          ' nVersion is reliable, use it...
      End If
    

Error raising and trapping is not to everyone's taste, so the second option might appeal to you.

Side effects when passing by reference

Bugs result when instances of parameters unexpectedly change their value. To put it at its simplest, parameters changing their value are a side effect, and side effects trip up programmers. If I call the function

Dim a, b
  a = f(b)

it is immediately apparent to me that a is likely to change, and probably b will not. But I cannot guarantee that without looking at the source code for the function f.

It is particularly unfortunate that the default parameter-passing convention is ByRef, because it means that you have to do extra typing to avoid ByRef parameters. Because of backward compatibility, I don't think there's any chance of this being changed. However, it has been suggested by the Visual Basic team that they could fill in the ByRefs automatically on listback in the editor so that people can see exactly what's happening. The problem is that this would alter all old code as it is brought into the editor and cause problems with source code control.