Visual Basic

Problems with Subclassing

Some Visual Basic functions are not suitable for subclassing. Some functions simply won't subclass because the function names have been made reserved words. Print is such an example, as were CDate and CVDate in Visual Basic 5. Ultimately, there is little that can be done about such functions except create functions with similar-but different-names. This requires that the developers be instructed to use the renamed function instead of the intrinsic function, and thus leaves the door open to inconsistencies within the code.

Functions that have multiple definitions but return a different result type (for example, Format and Format$) are also not possible to subclass fully. The problem here is that two functions are needed to subclass the function properly, but Visual Basic sees Public Function Format(…) As Variant and Public Function Format$(…) As String as being the same function and raises a compile-time error of a duplicate function definition. Here, the only option is to subclass the more generic function (in this example, the more generic function is Format, as it returns a Variant) and issue instructions to developers not to use Format$.

Other functions break Visual Basic's own rules on parameters. An example of this is InStr, which takes four arguments, of which the first and fourth arguments are optional. As Visual Basic's rules state that optional arguments must be at the end of a list of arguments, clearly we cannot subclass this function to match exactly the internal definition of it. To get around this, we either have four arguments, with the last two optional, or simply use a ParamArray of Variants as a single argument. Both of these solutions require more work within the new version of the function in order to work out which of the four arguments have been supplied.

One "nice to have" feature would be to wrap the subclassed functions in an ActiveX DLL such that the source code was "hidden" from the developers. Unfortunately, this currently isn't possible in Visual Basic. In the beginning of this section, I described the method Visual Basic uses to determine where to find the definition of a function. Remember the three references I listed that always appear at the top of the project references list? Unfortunately, there is no way to prevent those three references from being at the top of the list. This means that the reference to your ActiveX server with the subclassed functions is always below them in the list and, as a result, your subclassed functions are never called. It's a pity that this approach isn't possible, as it would not only hide the details of what extra functionality the subclassed functions contain, but it would also remove the clutter of the extra source code from the application.

by BrainBellupdated
Advertisement: