VBscript Is Frustrating

erich November 4th, 2005

I can’t stand the way VBScript handles non-values.  Consider the following:


strValue = SomeFunction()

If strValue = “” Then
‘ Do Something
Else
‘ Do Something Else
End If


This fails unless your SomeFunction() function specifically returns an empty string, such as:


strValue = SomeFunction()

If strValue = “” Then
‘ Do Something
Else
‘ Do Something Else
End If

Function SomeFunction()
SomeFunction = “”
End Function


This is because even an empty string is considered a value in VBScript, on which you can check the length and check for IsEmpty().  However, this doesn’t work if your function returns a variable that has no value, like this:


strValue = SomeFunction()

If strValue = “” Then
‘ Do Something
Else
‘ Do Something Else
End If

Function SomeFunction()
strValue = SomeOtherFunction()
SomeFunction = strValue
End Function


In this case, if the SomeOtherFunction() did not return a value, then the value of strValue is NULL.  In VBScript, a NULL is defined as “no valid data.”  So, the only way to validate this variable is to check for NULL:


strValue = SomeFunction()

If IsNull(strValue) Then
‘ Do Something
Else
‘ Do Something Else
End If

Function SomeFunction()
strValue = SomeOtherFunction()
SomeFunction = strValue
End Function


Because strValue does not hold valid data, IsNull() evaluates to TRUE.  Now, in the case of objects, where you expect a function to return an object, you have to use a completely different method:


Set objValue = SomeFunction()

If objValue Is Nothing Then
‘ Do Something
Else
‘ Do Something Else
End If

Function SomeFunction()
Set objValue = SomeOtherFunction()
Set SomeFunction = objValue
End Function


Strange, and not entirely intuitive, but there it is…

Trackback URI | Comments RSS

Leave a Reply

You must be logged in to post a comment.