Search code examples
javacoding-styleconventionsternary-operatorconditional-operator

Conditional (Ternary) Operator Code Style


int foo = bar > baz ? bar : baz;

int foo = someBoolean ? bar : baz;


int foo = (bar > baz) ? bar : baz;

int foo = (someBoolean) ? bar : baz;


int foo = (bar > baz) ? bar : baz;

int foo = someBoolean ? bar : baz;

I can't decide which of these three I should use. I can:

  1. Use no parentheses and risk bad readability in examples such as:

    min[0] = min[0] > pos.x ? pos.x : 0;

  2. Always use parentheses, but risk somewhat ugly code in short expressions:

    setValue(val + scrollBar.getBlockIncrement() * ((scrollsUp) ? -1 : 1));

  3. Stay somewhere in between and use parentheses when there are spaces in the condition, but not if the condition is just a boolean variable:

    min[0] = (min[0] > pos.x) ? pos.x : 0;

    setValue(val + scrollBar.getBlockIncrement() * (scrollsUp ? -1 : 1));


Solution

  • Oracles Code Conventions states the following

    return (condition ? x : y);
    

    .. and further

    if (a == b && c == d)     // AVOID!
    if ((a == b) && (c == d)) // RIGHT
    

    ...which is freely translated to

    return (someBoolean ? x : y);
    return ((x > y) ? x : y);
    

    .. although on a personal note I wouldn't mind relaxing a parenthesis or two. In the end it's still a subjective matter. If you feel adding/removing a parenthesis offers better readability, then by all means feel free to do so.