Ben Langhinrichs

Photograph of Ben Langhinrichs
E-mail address - Ben Langhinrichs






June, 2004
SMTWTFS
  01 02 03 04 05
06 07 08 09 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30

Search the weblog





























Genii Weblog


Civility in critiquing the ideas of others is no vice. Rudeness in defending your own ideas is no virtue.


Tue 15 Jun 2004, 11:18 PM
I searched, but it seems I have not blogged about this issue before.  Sigh!

The scenario
I ran into yet another case of incorrect implicit declaration of variables.  Simple examples would be:

Dim userName1, userName2 As String
Dim empNum1, empNum2, empNum3, count As Integer

The problem with the scenario
There seems to be an assumption that the variable type at the end of the line works for all the variables, but it just isn't true.  The variables userName1empNum1empNum2 and empNum3 are all created with type Variant, which clearly isn't what was intended.  The proper declaration would be 

Dim userName1 As String, userName2 As String
Dim empNum1 As Integer, empNum2 As Integer, empNum3 As Integer, count As Integer

or in longer form

Dim userName1 As String
Dim  userName2 As String
Dim empNum1 As Integer
Dim  empNum2 As Integer
Dim  empNum3 As Integer
Dim count As Integer

The obvious question about the problem with the scenario
But why bother?  Why not just leave them as Variant variables, which can hold String or Integer values anyway?

The answer to the obvious question about the problem with the scenario
Most of the time, this would work.  You script is not likely to break outright.  On the other hand, the performance is likely to be worse, because Variant cause overhead.  Memory usage will also be higher.  

And sometimes, things break.  A subroutine that expects a String might not appreciate a Variant.  An LSX that expects an Integer value may choke on a Variant.  A comparison with an uninitialized Variant isn't going to work where an uninitialized String might.  When these things happen, the signs won't be clear, the debugging may be costly, and the person who didn't recognize the problem when declaring the variables may have a devilishly difficult time understanding what is happening.

The recommendation in response to the answer to the obvious question about the problem with the scenario
Always declare your variables explicitly!

Copyright © 2004 Genii Software Ltd.