Benefits of using the conditional ?: (ternary) operator

后端 未结 17 1006
孤街浪徒
孤街浪徒 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 07:34

    I find it particularly helpful when doing web development if I want to set a variable to a value sent in the request if it is defined or to some default value if it is not.

    0 讨论(0)
  • 2020-11-22 07:34

    The advantage of the conditional operator is that it is an operator. In other words, it returns a value. Since if is a statement, it cannot return a value.

    0 讨论(0)
  • 2020-11-22 07:35

    One thing to recognize when using the ternary operator that it is an expression not a statement.

    In functional languages like scheme the distinction doesn't exists:

    (if (> a b) a b)

    Conditional ?: Operator "Doesn't seem to be as flexible as the if/else construct"

    In functional languages it is.

    When programming in imperative languages I apply the ternary operator in situations where I typically would use expressions (assignment, conditional statements, etc).

    0 讨论(0)
  • 2020-11-22 07:35

    I'd recommend limiting the use of the ternary(?:) operator to simple single line assignment if/else logic. Something resembling this pattern:

    if(<boolCondition>) {
        <variable> = <value>;
    }
    else {
        <variable> = <anotherValue>;
    }
    

    Could be easily converted to:

    <variable> = <boolCondition> ? <value> : <anotherValue>;
    

    I would avoid using the ternary operator in situations that require if/else if/else, nested if/else, or if/else branch logic that results in the evaluation of multiple lines. Applying the ternary operator in these situations would likely result in unreadable, confusing, and unmanageable code. Hope this helps.

    0 讨论(0)
  • 2020-11-22 07:36

    The scenario I most find myself using it is for defaulting values and especially in returns

    return someIndex < maxIndex ? someIndex : maxIndex;
    

    Those are really the only places I find it nice, but for them I do.

    Though if you're looking for a boolean this might sometimes look like an appropriate thing to do:

    bool hey = whatever < whatever_else ? true : false;
    

    Because it's so easy to read and understand, but that idea should always be tossed for the more obvious:

    bool hey = (whatever < whatever_else);
    
    0 讨论(0)
  • 2020-11-22 07:38

    I would basically recommend using it only when the resulting statement is extremely short and represents a significant increase in conciseness over the if/else equivalent without sacrificing readability.

    Good example:

    int result = Check() ? 1 : 0;
    

    Bad example:

    int result = FirstCheck() ? 1 : SecondCheck() ? 1 : ThirdCheck() ? 1 : 0;
    
    0 讨论(0)
提交回复
热议问题