Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional (Ternary) Operator Code Style [closed]

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));

like image 714
Konstantin Avatar asked Jul 06 '26 03:07

Konstantin


1 Answers

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.

like image 170
Johan Sjöberg Avatar answered Jul 09 '26 21:07

Johan Sjöberg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!