Proper way to declare an object?

  • Thread starter Thread starter Max Moor
  • Start date Start date
M

Max Moor

Hi All,

Is there a difference between dlaring a recordset object as:

Dim rs As New ADODB.Recordset

Or:

Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset


I've been doing the former, all through my code, but I notice many of
the examples given in the newsgroups done the latter way.

Thanks for the clarification,

Max
 
Great question!

The more "formal" coders with the most experience generally prefer:
Dim rs As ADODB.Recordset

some code might go here... then
Set rs = New ADODB.Recordset

The reason the above is preferred over the "new" keyword is that YOU CAN
better control when the object initialize event fires. If you create a class
object in ms-access (you can do that...), or use a existing object like the
above recordset..then a LOT of code can fire..and run when you setup the
object.

As it turns out..VB is quite good, and if you use the "new" keyword like:

dim rs As New ADODB.RecordSet

Then, the objects initialize and setup code DOE NOT run until you FIRST USE
the object SOMEWHERE in your code. That can be in several different places
in your code. So, VB kind of does the work for you...and the "new" does not
fire until you actually first use of the object in code. However, good
developers don't like surprises...so they tend to prefer NOT to declare the
object as new..and in code you can then CLEARLY see where the object is
FIRST used via the "new" keyword.

So, as a good coding standard tend to agree with those more experienced
developers.

I would not worry too much..but if you are looking to adopt a standard...I
would use the new in your code..and NOT via the dim statement. At least when
I come along and look at your code.it will be CLEAR where you intended the
first use of the object to occur.
 
...

I would not worry too much..but if you are looking to adopt a
standard...I would use the new in your code..and NOT via the dim
statement. At least when I come along and look at your code.it will be
CLEAR where you intended the first use of the object to occur.

...


Thanks for the quick answer Albert. What you say makes good sense. In the
code it goes! Thanks again...

- Max
 
Back
Top