Replacing nested if statements

前端 未结 11 1909
春和景丽
春和景丽 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:35

    One example I always try to do is replace heavily nested if's like this (actually this one's not too bad but I've seen them up to 8 or 9 levels deep in the wild):

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

    with this:

    switch (i) {
        case 1:
            // action 1
            break;
        case 2:
            // action 2
            break;
        case 3:
            // action 3
            break;
        default:
            // action 4
            break;
    }
    

    I also try to keep the actions as small as possible (function calls are best for this) to keep the switch statement compressed (so you don't have to go four pages ahead to see the end of it).

    Decision tables, I believe, are simply setting flags indicating what actions have to be taken later on. The "later on" section is simple sequencing of actions based on those flags. I could be wrong (it won't be the first or last time :-).

    An example would be (the flag-setting phase can be complicated if's since its actions are very simple):

    switch (i) {
        case 1:
            outmsg = "no paper";
            genmsg = true;
            mailmsg = true;
            phonemsg = false;
            break;
        case 2:
            outmsg = "no ink";
            genmsg = true;
            mailmsg = true;
            phonemsg = false;
            break;
        default:
            outmsg = "unknown problem";
            genmsg = true;
            mailmsg = true;
            phonemsg = true;
            break;
    }
    
    if (genmsg)
        // Send message to screen.
    if (mailmsg)
        // Send message to operators email address.
    if (phonemsg)
        // Hassle operators mobile phone.
    

提交回复
热议问题