Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nested ternary operator vs nested if else, which is better in readability purpose

I found code in code review which was written by my team member. It contains nested ternary operator. I told him to use if else if there is more than one nesting for readability purpose. We had argue on that.

following is code

ColorEnum color = opacity == Opacity.FIVE? ColorEnum.BLACK : 
                opacity == Opacity.TEN? ColorEnum.WHITE :
                    opacity == Opacity.FIFTY? ColorEnum.RED :
                        opacity == Opacity.TWENTY? ColorEnum.BLUE :
                            opacity == Opacity.FIFTEEN? ColorEnum.PURPLE : null;

And this code is changing as new configurations come.

So What is better here? ternary operator or if else?

like image 773
nilesh Avatar asked Dec 04 '22 02:12

nilesh


1 Answers

Just reformatting your code makes it quite clear:

ColorEnum color = 
          opacity == Opacity.FIVE    ? ColorEnum.BLACK
       :  opacity == Opacity.TEN     ? ColorEnum.WHITE 
       :  opacity == Opacity.FIFTY   ? ColorEnum.RED 
       :  opacity == Opacity.TWENTY  ? ColorEnum.BLUE 
       :  opacity == Opacity.FIFTEEN ? ColorEnum.PURPLE 
       :  null;

LISP adopts the cond construct which has both the same structure and the same semantics, and is considered good practice. As an aside, Clojure also supports a form which tests the value of a single expression with a single predicate applied to different values (one for each clause) and calls it condp—that would be a perfect match for your use case.

The idiom with the ternary operator has the advantage over an if-else cascade for being an expression so you need only a single statement to assign it to the variable. if-else will force you to pull the assignment into each then clause, introducing more boilerplate and more opportunity to fail on correctness.

A switch statement could also be considered as an alternative, but it would have the following deficiencies:

  • like if-else, it is not an expression;

  • you are restricted to just different constant values of a single expression (the type of the expression being quite constrained, too).

  • it's prone to bugs due to the boilerplate break missing somewhere.

like image 109
Marko Topolnik Avatar answered Jan 16 '23 13:01

Marko Topolnik