Wednesday, March 23, 2011

Refactoring the Shortcut IF statement

static void Main(string[] args)
    {

    // Given three expressions...
    bool Expression1 = true;
    bool Expression2 = true;
    bool Expression3 = true;

    
    /* You may run across code that looks something like this.
     * Using this type of construct has a bad smell, 
     * since the if/else shortcut has multiple expressions.
     */
    bool x;
    x = (Expression1) ? ((Expression2) ? ((Expression3) ? true : false) : false) : false;
    Console.WriteLine(x);  // Writes True

    
    /* By expanding it into if statements you can determine
     * where the common result is -- in this case "false" --
     * is found, and why.
     */
    if (Expression1)
        if (Expression2)
            if (Expression3)
                x = true;
            else
                x = false;
        else
            x = false;
    else
        x = false;
    Console.WriteLine(x);  // Writes True


    
    /* Since x is only set to True when all 
     * three expressions are true,
     * the code can be refactored as follows:
     */

    x = false;
    if (Expression1 && Expression2 && Expression3) 
        x = true;
    Console.WriteLine(x);  // Writes True


    // Now, you can refactor the code so that it 
    // makes better sense.
     
    x = (Expression1 && Expression2 && Expression3) ? true : false;
    Console.WriteLine(x);  // Writes True


    }

No comments:

Post a Comment