Saturday, December 26, 2009

Your First Class Module

Creating a class in Visual Basic is straightforward: just issue an Add Class Module command from the Project menu. A new code editor window appears on an empty listing. By default, the first class module is named Class1, so the very first thing you should do is change this into a more appropriate name. In this first example, I show how to encapsulate personal data related to a person, so I’m naming this first class CPerson.
The first version of our class includes only a few properties. These properties are exposed as Public members of the class module itself, as you can see in this code and also in Figure on the following page:
‘ In the declaration section of the CPerson class module
Public FirstName As String
Public LastName As String




This is a very simple class, but it’s a good starting point for experimenting with some interesting concepts, without being distracted by details. Once you have created a class module, you can declare an object variable that refers to an instance of that class:
‘ In a form module
Private Sub cmdCreatePerson_Click()
Dim pers As CPerson ‘ Declare.
Set pers = New CPerson ‘ Create.
pers.FirstName = "John" ‘ Assign properties.
pers.LastName = "Smith"
Print pers.FirstName & " " & pers.LastName ‘ Check that it works.
End Sub
The code’s not very impressive, admittedly. But remember that here we’re just laying down concepts whose real power will be apparent only when we apply them to more complex objects in real-world applications.
Auto-instancing object variables
Unlike regular variables, which can be used as soon they have been declared, an object variable must be explicitly assigned an object reference before you can invoke the object’s properties and methods. In fact, when an object variable hasn’t been assigned yet, it contains the special Nothing value: In other words, it doesn’t contain any valid reference to an actual object. To see what this means, just try out this code:
Dim pers As CPerson ‘ Declare the variable,
‘ Set pers = New CPerson ‘ but comment out the creation step.
Print pers.FirstName ‘ This raises an error 91 – "Object variable
‘ or With block variable not set"
In most cases, this behavior is desirable because it doesn’t make much sense to print a property of an object that doesn’t exist. A way to avoid the error is to test the current contents of an object variable using the Is Nothing test:
‘ Use the variable only if it contains a valid object reference
If Not (pers Is Nothing) Then Print pers.FirstName
In other cases, however, you just want to create an object, any object, and then assign its properties. In these circumstances, you might find it useful to declare an auto-instancing object variable using the As New clause:
Dim pers As New CPerson ‘ Auto-instancing variable
When at run time Visual Basic encounters a reference to an auto-instancing variable, it first determines whether it’s pointing to an existing object and creates a brand new instance of the class if necessary. Auto-instancing variables have virtues and liabilities, plus a few quirks you should be aware of:
• Auto-instancing variables obviously reduce the amount of code you need to write to be up and running with your classes. For this reason, they’re often valuable during the prototyping phase.
• Auto-instancing variables can’t be tested against the Nothing value. In fact, as soon as you use one in the Is Nothing test, Visual Basic relentlessly creates a new instance and the test always returns False. In some cases, this could be the decisive factor in whether to stay clear of auto-instancing variables.
• Auto-instancing variables tend to eliminate errors, but sometimes this is precisely what you don’t need. In fact, during the development phase you want to see errors because they’re the symptoms of other serious flaws in the code logic. Auto-instancing variables make the debugging step a little more obscure because you can never be sure when and why an object was created. This is probably the most persuasive reason not to use auto-instancing variables.
• You can’t declare an auto-instancing variable of a generic type, such as Object, Form, or MDIForm because Visual Basic must know in advance which kind of object should be created when it references that variable for the first time.
• In some complex routines, you might declare a variable but never actually use it: this happens all the time with standard variables and with object variables too, but it creates a problem with regular (non-auto-instancing) object variables. In fact, if you create the object with a Set command at the beginning of a procedure, you might be creating an object—thus taking both time and memory—for no real purpose. On the other hand, if you delay the creation of an object until you actually need it, you could soon find yourself drowning in a sea of Set commands, each preceded by an Is Nothing test to avoid re-creating an object instanced previously. By comparison, auto-instancing variables are automatically created by Visual Basic only if and when they are referenced: In all other cases, no time or memory will be wasted without reason. This is probably the situation in which auto-instancing variables are most useful.
Finally, each time Visual Basic references an auto-instancing variable, it incurs a small performance hit because it has to check whether it’s Nothing. This overhead is usually negligible, but in some time-critical routines it could affect the overall time.
In summary, auto-instancing variables often aren’t the best choice, and in general I advise you not to use them. Most of the code shown in this chapter doesn’t make use of auto-instancing variables, and you can often do without them in your own applications as well.

No comments:

Post a Comment