2012-02-25

Code Patterns: Setting Booleans

This comes up often enough that it deserves some thought: setting booleans.  The two most used booleans are the .Visible and .Enable properties available on all UI Forms and Web Forms controls from Microsoft.  There are four forms for setting these (a and b are of similar type; bc is a boolean):

In C-ish:

        // form one
        if (a == b)
            bc = true;
        else
            bc = false;

        // form two
        bc = false;
        if (a == b)
            bc = true;

        // form three
        bc = (a == b) ? true : false;

        // form four
        bc = (bool)(a == b);

In Visual Basic:

        'Form one
        If a = b Then
            bc = True
        Else
            bc = False
        End If

        'Form two
        bc = False
        If a = b Then bc = True

        'Form three
        bc = If(a = b, True, False)

        'Form four
        bc = CBool(a = b)

I advocate form four in both languages.  Without the "If" keyword, directive, or function, there is no zero-bit check in the assembly with the subsequent code jumps.  Even if the compiler is efficient and recodes these scenarios, then I still favor form four, because it is concise. 

I run across this frequently when I'm reviewing code, and I hope that this may remove one more rewrite in future reviews.

-- Steve

No comments:

Post a Comment