Wednesday, December 14, 2011

Mixed Variable Types

Some languages like VB and VBScript allow for what is commonly referred to as "evil coercion" meaning that the system will do it's best to do automatic type conversion between two variable types.

This can be helpful in situations like this:
Dim x As Integer
Dim s As String

s = "7"

x = s 'No need to call Convert functions

But this can also cause major problems, especially in VBScript where variables aren't explicitly typed and everything is a "Variant", meaning a variable that can dynamically change it's internal type.

In these cases if you don't explicitly stick to rules of variable handling, initialization and comparison, you can run into serious logical errors, as well as confuse anyone trying to troubleshoot your code.

Sad Code:
'Variable is prefixed with "int"
'and value is initialized to a number
'but in quotes so it's treated as a string
Dim intNew : intNew = "0" 

'The database bit field is a Boolean,
'so the variant intNew should change to act like a Boolean
intNew = objRSLeadStage("bNew") 

'What's going to happen here?
'Is intNew a string, boolean or number?
If (intNew = "True") Then

Oddly enough, the above Sad Code works, in the sense that the comparison between the string value "True" coerces to the Boolean value True for the If statement.

The intNew variable here clearly has an identity crisis, and anyone trying to debug this code amongst a thousand other lines is most likely going to end up pulling there hair out asking WHY?

So remember that when you're working with dynamic variable types like Variants or Objects, and languages that perform evil coercion you should be VERY strict with how you handle your data types and variable names to avoid confusion.

Happy Code:
Dim bNew : bNew = False

bNew = CBool(objRSLeadStage("bNew"))

If (bNew) Then

As you can see here, there is no confusion in any area as to the behavior of your variable.