Avoiding several nested if statements

我怕爱的太早我们不能终老 提交于 2021-02-11 12:42:45

问题


I'm writing a function that pushes specific (predefined) variables to predefined arrays based on the status of 4 variables, all of which are ranging from 1 to 5 (they are the results of radio buttons pressed on our web page).

If the variables equal A, B, C and D, the predefined variables to predefined arrays X, Y and Z are defined by:

X = the combination of A and B.

Y = the combination of C and D.

Z = the combination of A, B, C and D.

Below is my realization of a solution to said problem (A, B, C and D are motivation, orientation, influence and relevance), using nested if/else statements. However, I find this solution inelegant. I both want to write cleaner code, and leave the code more readable for my fellow coworkers. What would be the most elegant way to type this out? Should I use functions, switch statements, something else?

Below is the entire function:

function getRadioParameters (influence, relevance, motivation, orientation) {
    if (influence >= 3) {
        if (relevance >= 3) {
            influenceRelevanceArr.push(highInfluenceHighRelevance);
            if (motivation >= 3) {
                if (orientation >= 3) {
                    motivationOrientationArr.push(highMotivationHighOrientation);
                    stkImagesArr.push(getImage('HHHH'));
                }
                else if (orientation < 3) {
                    motivationOrientationArr.push(highMotivationLowOrientation);
                    stkImagesArr.push(getImage('HHHL'));
                }
                else {
                    motivationOrientationArr.push('');
                    stkImagesArr.push('');
                    console.log('problem with orientation. It is = ', orientation)
                }
            }
            else if (motivation < 3) {
                if (orientation >= 3) {
                    motivationOrientationArr.push(lowMotivationHighOrientation);
                    stkImagesArr.push(getImage('HHLH'));
                }
                else if (orientation<3) {
                    motivationOrientationArr.push(lowMotivationLowOrientation);
                    stkImagesArr.push(getImage('HHLL'));
                }
                else {
                    motivationOrientationArr.push('');
                    stkImagesArr.push('');
                    console.log('problem with orientation. It is = ', orientation);
                }
            }
            else {
                motivationOrientationArr.push('');
                stkImagesArr.push('');
                console.log('problem with motivation. It is = ', motivation);
            }

        }
        else if (relevance < 3) {
            influenceRelevanceArr.push(highInfluenceLowRelevance);
            if (motivation >= 3) {
                if (orientation >= 3) {
                    motivationOrientationArr.push(highMotivationHighOrientation);
                    stkImagesArr.push(getImage('HLHH'));
                }
                else if (orientation < 3) {
                    motivationOrientationArr.push(highMotivationLowOrientation);
                    stkImagesArr.push(getImage('HLHL'));
                }
                else {
                    motivationOrientationArr.push('');
                    stkImagesArr.push('');
                    console.log('problem with orientation. It is = ', orientation)
                }
            }
            else if (motivation < 3) {
                if (orientation >= 3) {
                    motivationOrientationArr.push(lowMotivationHighOrientation);
                    stkImagesArr.push(getImage('HLLH'));
                }
                else if (orientation<3) {
                    motivationOrientationArr.push(lowMotivationLowOrientation);
                    stkImagesArr.push(getImage('HLLL'));
                }
                else {
                    motivationOrientationArr.push('');
                    stkImagesArr.push('');
                    console.log('problem with orientation. It is = ', orientation);
                }
            }
            else {
                motivationOrientationArr.push('');
                stkImagesArr.push('');
                console.log('problem with motivation. It is = ', motivation);
            }

        }
        else {
            influenceRelevanceArr.push('');
            motivationOrientationArr.push('');
            stkImagesArr.push('');
            console.log('problem with relevance. It is =', relevance);
        }
    }
    else if (influence < 3) {
        if (relevance >= 3) {
            influenceRelevanceArr.push(lowInfluenceHighRelevance);
            if (motivation >= 3) {
                if (orientation >= 3) {
                    motivationOrientationArr.push(highMotivationHighOrientation);
                    stkImagesArr.push(getImage('LHHH'));
                }
                else if (orientation < 3) {
                    motivationOrientationArr.push(highMotivationLowOrientation);
                    stkImagesArr.push(getImage('LHHL'));
                }
                else {
                    motivationOrientationArr.push('');
                    stkImagesArr.push('');
                    console.log('problem with orientation. It is = ', orientation)
                }
            }
            else if (motivation < 3) {
                if (orientation >= 3) {
                    motivationOrientationArr.push(lowMotivationHighOrientation);
                    stkImagesArr.push(getImage('LHLH'));
                }
                else if (orientation<3) {
                    motivationOrientationArr.push(lowMotivationLowOrientation);
                    stkImagesArr.push(getImage('LHLL'));
                }
                else {
                    motivationOrientationArr.push('');
                    stkImagesArr.push('');
                    console.log('problem with orientation. It is = ', orientation);
                }
            }
            else {
                motivationOrientationArr.push('');
                stkImagesArr.push('');
                console.log('problem with motivation. It is = ', motivation);
            }

        }
        else if (relevance < 3) {
            influenceRelevanceArr.push(lowInfluenceLowRelevance);
            if (motivation >= 3) {
                if (orientation >= 3) {
                    motivationOrientationArr.push(highMotivationHighOrientation);
                    stkImagesArr.push(getImage('LLHH'));
                }
                else if (orientation < 3) {
                    motivationOrientationArr.push(highMotivationLowOrientation);
                    stkImagesArr.push(getImage('LLHL'));
                }
                else {
                    motivationOrientationArr.push('');
                    stkImagesArr.push('');
                    console.log('problem with orientation. It is = ', orientation)
                }
            }
            else if (motivation < 3) {
                if (orientation >= 3) {
                    motivationOrientationArr.push(lowMotivationHighOrientation);
                    stkImagesArr.push(getImage('LLLH'));
                }
                else if (orientation<3) {
                    motivationOrientationArr.push(lowMotivationLowOrientation);
                    stkImagesArr.push(getImage('LLLL'));
                }
                else {
                    motivationOrientationArr.push('');
                    stkImagesArr.push('');
                    console.log('problem with orientation. It is = ', orientation);
                }
            }
            else {
                motivationOrientationArr.push('');
                stkImagesArr.push('');
                console.log('problem with motivation. It is = ', motivation);
            }

        }
        else {
            influenceRelevanceArr.push('');
            motivationOrientationArr.push('');
            stkImagesArr.push('');
            console.log('problem with relevance. It is =', relevance);
        }
    }

}

Thank you!


回答1:


Here is an example of abstracting it away using a function:

//X = the combination of A and B.
//Y = the combination of C and D.
//Z = the combination of A, B, C and D.
// in this example:
// A > 5, B > 10, C> 15, D > 20

function returnCharacteristic(input) {
  if (input[0] > 5 && input[1] > 10 && input[2] > 15 && input[3] > 20) {
    return 'Z';
  }
  if (input[2] > 15 && input[3] > 20) {
    return 'Y';
  }
  if (input[0] > 5 && input[1] > 10) {
    return 'X';
  }
  
  return 'No criterea met';


}

let test1 = [10, 5, 33, 5];
let test2 = [10, 15, 32, 50];
let test3 = [20, 20, 10, 9];
let test4 = [0, 5, 50, 50];


console.log(returnCharacteristic(test1));
console.log(returnCharacteristic(test2));
console.log(returnCharacteristic(test3));
console.log(returnCharacteristic(test4));

In this example I used some random conditions to determine if a criteria was met but you of course need to tailor them to your needs. Usually when your code is deeply nested like yours you have made a code designing mistake. Usually there are more elegant solutions which require you to refactor the code a bit.

Deeply nesting code increases the difficulty of reasoning about it which not only makes your code less maintainable but also increases the chances of introducing bugs. And even when there are bugs it is harder to debug is deeply nested code.

Hopefully this was helpful.




回答2:


If i understand what you're trying to do right, i think you can do something like this

    var obj = {
        "highInfluence_highRelevance": highInfluenceHighRelevance,
        "highInfluence_lowRelevance": highInfluenceLowRelevance,
        "lowInfluence_highRelevance": lowInfluenceHighRelevance,
        "lowInfluence_lowRelevance": lowInfluenceLowRelevance,
        "highMotivation_highOrientation": highMotivationHighOrientation,
        "highMotivation_lowOrientation": highMotivationLowOrientation,
        "lowMotivation_highOrientation": lowMotivationHighOrientation,
        "lowMotivation_lowOrientation": lowMotivationLowOrientation
    }

    var imgStr = "";

    function evaluateRadioParameters(num) {
        if (num >= 3) return "high";
        else if (num < 3) return "low";
        return "";
    }

    function setimgStr(num, str) {
        if (num >= 3) imgStr += "H";
        else if (num < 3) imgStr += "L";
       else console.log('problem with ' + str + '. It is = ', num);
    }

    function getRadioParameters(influence, relevance, motivation, orientation) {
        var influenceStr = evaluateRadioParameters(influence);
        var relevanceStr = evaluateRadioParameters(relevance);
        var motivationStr = evaluateRadioParameters(motivation);
        var orientationStr = evaluateRadioParameters(orientation);

        if (influenceStr == "" || relevanceStr == "") {
            influenceRelevanceArr.push("");
        } else {
            influenceRelevanceArr.push(obj[influenceStr + "Influence_" + relevanceStr + "Relevance"]);
        }

        if (motivationStr == "" || orientationStr == "") {
            motivationOrientationArr.push("");
        } else {
            motivationOrientationArr.push(obj[influenceStr + "Influence_" + relevanceStr + "Relevance"]);
        }

        if (influenceStr == "" || relevanceStr == "" || motivationStr == "" || orientationStr == "")
            stkImagesArr.push('');
        else {
            setimgStr(influence, "influence");
            setimgStr(relevance, "relevance");
            setimgStr(motivation, "motivation");
            setimgStr(orientation, "orientation");
            stkImagesArr.push(getImage(imgStr));
        }

    }



回答3:


It might be easier to get each individual value separately, then combine them somehow - it all depends on your data structures. From what I see so far, I think you can do something like this (this is high level, you'll have to fill in the full details yourself):

function getRadioParameters(influence, relevance, motivation, orientation) {
  const inf = gague(influence, 'highInfluence', 'lowInfluence');
  const rel = gague(relevance, 'highRelevance', 'lowRelevance');
  const mot = gague(motivation, 'highMotivation', 'lowMotivation');
  const ori = gague(orientation, 'highOrientation', 'lowOrientation');
  const allVals = [inf, rel, mot, ori];
  const finalValues = getFinalValues(allVals);

  return finalValues;
}

function getFinalValues(allVals) {
  const finalValues = { img: '', char: '' };

  allVals.forEach(function(item) {
    finalValues.img += item.img;
    finalValues.char += item.char;
  });

  return finalValues;
}

function gague(param, high, low) {
  if (param >= 3) return { char: high, img: 'H' };
  return { char: low, img: 'L' };
}

let result = getRadioParameters(3, 3, 3, 3);
console.log(result);

result = getRadioParameters(3, 3, 3, 0);
console.log(result);

result = getRadioParameters(3, 3, 0, 3);
console.log(result);

result = getRadioParameters(3, 0, 3, 3);
console.log(result);

also, if you're using ES6/7 you can simplify the code even more:

function getRadioParameters(influence, relevance, motivation, orientation) {
  const inf = gague(influence, 'HIGH-influence', 'LOW-influence');
  const rel = gague(relevance, 'HIGH-relevance', 'LOW-relevance');
  const mot = gague(motivation, 'HIGH-motivation', 'LOW-motivation');
  const ori = gague(orientation, 'HIGH-orientation', 'LOW-orientation');
  const allVals = [inf, rel, mot, ori];
  const finalValue = allVals.reduce(getFinalValue, { img: '', char: '' });

  return finalValue;
}

function getFinalValue(prev, current) {
  const img = prev.img + current.img;
  const char = prev.char + ' ' + current.char;
  return { img, char };
}

function gague(param, high, low) {
  if (param >= 3) return { char: high, img: 'H' };
  return { char: low, img: 'L' };
}

let result = getRadioParameters(3, 3, 3, 3);
console.log(result);

result = getRadioParameters(3, 3, 3, 0);
console.log(result);

result = getRadioParameters(3, 3, 0, 3);
console.log(result);

result = getRadioParameters(3, 0, 3, 3);
console.log(result);


来源:https://stackoverflow.com/questions/51896916/avoiding-several-nested-if-statements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!