Are multiple conditional operators in this situation a good idea?

前端 未结 21 2932
名媛妹妹
名媛妹妹 2020-12-15 06:23

I just saw this block of code on the Wikipedia article on conditional operators:

Vehicle new_vehicle = arg == \'B\' ? bus      :
                      arg ==         


        
21条回答
  •  难免孤独
    2020-12-15 07:15

    Purely practical:

    Plus: The ternary sequence is more flexible, and can be used to avoid the limitations of switch, you could use other operators (e.g. <=, >=) or any other tests, including e.g. string comparisons.

    x = IsEven(arg) ?  0 : 
        (arg < 0)   ? -1 : 1; // or whatever
    

    Also, if the switch is a performance bottleneck and you have uneven probabilities, you can force the likeliest tests being done first (due to the not evaluated guarantee for the path not chosen).

    So-So Unlike a switch statement, order is important (unless you stick to ==). That can be an advantage, but being otherwise similar to switch that might be misleading when the maintainer is unfamiliar with the concept or in a hurry.

    Many developers may shy away because they aren't sure about the details (which terms will be evaluated, is the rpecedence of the operators ok?) - However, if your developer pool won't grasp a well-presented example, you might have problems that can't be solved by banning ternary operators.

    Minus It isn't as common as switch, thus the optimizer might not treat it the same. Optimizers are know to select the best fit implementation for a switch (table, binary search, comparison sequence, or any combination of this). Optimizers can't reaarange wevaluaiton order, and are less likely to support a table lookup here.

    Requires good formatting to be easily recognizable (lining up the '?' and ':') - Sucks when you use tabs.

    Aesthetics

    I like it for its precision and succinctness, close to mathematical notations. However, that might as well be used against it. It's probably an eyebrow raiser at code reviews, because it is less common and more brittle.

提交回复
热议问题