Replacing nested if statements

前端 未结 11 1927
春和景丽
春和景丽 2020-12-23 20:44

This is related to a chapter from beautiful code. And in that chapter I read about the nested ifs.

The author was talking about deeply nested if

11条回答
  •  感动是毒
    2020-12-23 21:27

    Decision tables are where you store the conditional logic in a data structure rather than within the code itself.

    So instead of this (using @Pax's example):

    if (i == 1) {
        // action 1
    } else {
        if (i == 2) {
            // action 2
        } else {
            if (i == 3) {
                // action 3
            } else {
                // action 4
            }
        }
    }
    

    you do something like this:

    void action1()
    {
        // action 1
    }
    
    void action2()
    {
        // action 2
    }
    
    void action3()
    {
        // action 3
    }
    
    void action4()
    {
        // action 4
    }
    
    #define NUM_ACTIONS 4
    
    // Create array of function pointers for each allowed value of i
    void (*actions[NUM_ACTIONS])() = { NULL, action1, action2, action3 }
    
    // And now in the body of a function somewhere...
    if ((i < NUM_ACTIONS) && actions[i])
        actions[i]();
    else
        action4();
    

    If the possibilities for i are not low-numbered integers then you could create a lookup table instead of directly accessing the ith element of the actions array.

    This technique becomes much more useful than nested ifs or switch statements when you have a decision over dozens of possible values.

提交回复
热议问题