How to test boolean expressions in VBScript

booleanboolean-expressionvbscript

I am trying to convert the code from https://stackoverflow.com/questions/4554014/how-to-examine-and-manipulate-iis-metadata-in-c to VBVcript.

My problem is with this code:

Function LocateVirtualDirectory(ByVal siteName, ByVal vdirName)
    On Error Resume Next
    Dim site
    For Each site in w3svc
        If (site.KeyType = "IIsWebServer") And (site.ServerComment = siteName) Then
            Set LocateVirtualDirectory = GetObject(site.Path & "/ROOT/" & vdirName)
            Exit Function
        End If
    Next
End Function

If site.ServerComment is Empty, then the whole boolean expression receives the value Empty, which is not False and hence the then-statement is entered.

What is the right way to write that expression? The shorter the better.

Thanks.

Best Answer

I would simply nest the If statements, and insert an additional check to guard against the condition where ServerComment is Empty. I've also extracted the value of site.ServerComment into the temporary variable comment so that you won't be accessing the property twice.

For example:

Function LocateVirtualDirectory(ByVal siteName, ByVal vdirName)
    On Error Resume Next
    Dim site
    Dim comment
    For Each site in w3svc
        If site.KeyType = "IIsWebServer" Then
            comment = site.ServerComment
            If (comment <> Empty) And (comment = siteName) Then
                Set LocateVirtualDirectory = GetObject(site.Path & "/ROOT/" & vdirName)
                Exit Function
            End If
        End If
    Next
End Function

Another benefit of nesting the If statements is to short-circuit the evaluation. VBScript (and VB 6) don't short-circuit conditional evaluations—the And operator works as a logical one, requiring that both sides of the conditional are tested in order for a result to be determined. Because there's no reason to check the ServerComment if the KeyType doesn't match, you'll gain a little in performance by short-circuiting the expression. The only way to achieve that in VBScript is nesting (there is no AndAlso).

I should also point out that there is absolutely no point to testing if a value = True. You can simply rewrite (site.ServerComment = siteName) = True as site.ServerComment = siteName, and achieve exactly the same result. It took me at least several minutes to figure out what your original code even did because that's such an unnatural way of writing conditionals.