Benefits of using the conditional ?: (ternary) operator

后端 未结 17 1207
孤街浪徒
孤街浪徒 2020-11-22 06:55

What are the benefits and drawbacks of the ?: operator as opposed to the standard if-else statement. The obvious ones being:

Conditional ?: Operator

17条回答
  •  执念已碎
    2020-11-22 08:00

    The conditional operator is great for short conditions, like this:

    varA = boolB ? valC : valD;
    

    I use it occasionally because it takes less time to write something that way... unfortunately, this branching can sometimes be missed by another developer browsing over your code. Plus, code isn't usually that short, so I usually help readability by putting the ? and : on separate lines, like this:

    doSomeStuffToSomething(shouldSomethingBeDone()
        ? getTheThingThatNeedsStuffDone()
        : getTheOtherThingThatNeedsStuffDone());
    

    However, the big advantage to using if/else blocks (and why I prefer them) is that it's easier to come in later and add some additional logic to the branch,

    if (shouldSomethingBeDone()) {
        doSomeStuffToSomething(getTheThingThatNeedsStuffDone());
        doSomeAdditionalStuff();
    } else {
    doSomeStuffToSomething(getTheOtherThingThatNeedsStuffDone());
    }
    

    or add another condition:

    if (shouldSomethingBeDone()) {
        doSomeStuffToSomething(getTheThingThatNeedsStuffDone());
        doSomeAdditionalStuff();
    } else if (shouldThisOtherThingBeDone()){
        doSomeStuffToSomething(getTheOtherThingThatNeedsStuffDone());
    }
    

    So, in the end, it's about convenience for you now (shorter to use :?) vs. convenience for you (and others) later. It's a judgment call... but like all other code-formatting issues, the only real rule is to be consistent, and be visually courteous to those who have to maintain (or grade!) your code.

    (all code eye-compiled)

提交回复
热议问题