Listing Two Ways to Use an Object

Sub TestSimp1eLoan()

' declare a loan variable and explicitly ' create the object that the variable ' will refer to. Dim objLoanl As New SimpleLoan

' declare a loan variable Dim objLoan2 As SimpleLoan

' create the object that objLoan2

Set objLoan2 = New SimpleLoan

' demonstrate that the two ' loans are separate objects objLoanl.LoanNumber = 1 objLoan2.LoanNumber = 2

Debug.Print "objLoanl.LoanNumber is: " & objLoanl.LoanNumber Debug.Print "objLoan2.LoanNumber is: " & objLoan2.LoanNumber

' terminate the objects and ' free the memory associated with ' the object variables Set objLoanl = Nothing Set objLoan2 = Nothing End Sub

Figure 11.3

By developing and using classes, you automatically get the benefit of having your classes appear in the Auto List Members list.

Figure 11.3

By developing and using classes, you automatically get the benefit of having your classes appear in the Auto List Members list.

This listing produces the following output:

objLoanl.LoanNumber is: 1 objLoan2.LoanNumber is: 2

You may be tempted to use the method used for instantiating objLoan1. After all, it takes only one line of code to do this versus two lines of code for the method used with objLoan2. In many cases, absolutely nothing is wrong with this. However, it would be a good exercise for you to step through this code in Break mode and observe the behavior of each method. What you'll find is that when you use the first method, the object is not instantiated when you declare the variable with the New keyword. Instead, it's instantiated the first time the variable is used. However, the second method instantiates the object in the statement that sets the variable to refer to a newly created object.

The point to remember here is that when you use the one-line method of instantiation, it can be difficult to know when the object is instantiated because it happens implicitly the first time the object is used. The two-line method is much clearer because it makes instantiation an explicit occurrence.

I prefer to use the one-line method only in small simple procedures where the object is instantiated and terminated all in the same procedure and is not passed to other procedures as a variable. Otherwise, for debugging and mental simplification purposes, I prefer the two-line method.

0 0

Post a comment