Multiple conditions in the ternary operator safe?

前端 未结 6 1569
情话喂你
情话喂你 2021-01-17 09:22

I have seen advice that says the ternary operator must not be nested.

I have tested the code below and it works okay. My question is, I haven\'t seen the ternary op

6条回答
  •  日久生厌
    2021-01-17 10:11

    You do not need the ternary if you are going to return true or false. Quoting the manual:

    The expression (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1 evaluates to TRUE, and expr3 if expr1 evaluates to FALSE.

    This means

    $res = (($rule1 == true) && ($rule2 == false) && ($rule3 == true));
    

    will assign true or false already. Also, if dont care about $rule being booleans, you dont need the comparison with ==. You also dont need the braces, e.g.

    $res = $rule1 && !$rule2 && $rule3;
    

    is the same as your initial ternary.

    A good practise when you have multiple expressions like that is to hide the actual comparison behind a meaningful method or function name, e.g.

    function conditionsMet($rule1, $rule2, $rule3) {
        return $rule1 && !$rule2 && $rule3;
    }
    

    and then you can do

    if (conditionsMet($rule1, $rule2, $rule3)) {
        // do something
    }
    

    Of course, conditionsMet isnt that meaningful. A better example would be something like isSummerTime or isEligibleForDiscount and so on. Just express what the rules express in the method name.

    You might also be interested in Simplifying Conditional Expressions from the book Refactoring - Improving the design of existing code.

提交回复
热议问题