William -
Best practice is not to do this:
[tab]Dim objMyInstance as New clsMyObject
because you have less control over when the object is created and destroyed. Try doing something like this for more robust code:
[tt]
Public Function MyFunc() as Boolean
Dim objMyInstance as clsMyObject
[tab]On Error Goto MyFunc_ErrHandler
[tab]MyFunc = True 'Assume failure
[tab]Set objMyInstance = New clsMyObject
[tab]'
[tab]' Use your instance here
[tab]'
[tab]MyFunc = False ' return success
[tab]Goto MyFunc_Cleanup
MyFunc_ErrHandler:
[tab]' Log your error. I'd write a common error logging
[tab]' routine to do this
[tab]' Fall through into Cleanup
MyFunc_Cleanup:
[tab]If Not objMyInstance is Nothing Then
[tab][tab]' call any close methods for objMyInstance here
[tab][tab]set objMyInstance = Nothing
[tab]End If
End Function
[/tt]
This is much better because you're explicitly creating and destroying the object instance. If you use the "Dim as New" style, if you access the object variable after setting it to Nothing, a new instance gets created for you by the VB runtime, and you have no control over the state (no methods are called which could set internal state), and you don't know what it's going to do. Especially in a COM+/MTS setting, since the Class_Initialize only gets called once there. Here's an example of this (bad) behavior:
[tt]
'''clsBankAccount
Public Balance as currency
Public Sub Deposit(DepositAmt as Currency)
[tab]Balance = Balance + DepositAmt
End Sub
''' Code that uses the bank account object
Public Sub WorkWithBA
Dim objBA as New clsBankAccount
objBA.Balance = 50 'Set initial balance
objBA.Deposit(100)
Set objBA = Nothing 'Accidentally set it to Nothing
objBA.Deposit(200)
End Sub
[/tt]
In this (contrived, I admit it) example, the Bank Account will have $200 in it before the subroutine ends, not the expected $350. When Deposit is called the second time, a new instance of clsBankAccount is created for you behind the scenes, and it's member variables (Balance) are set to their default values (if they have any), which is 0 for a currency.
Hope this helps, and good luck on the interviews.
Chip H.