Suddenly, the code below came out, and it was a story that I was wondering.
String str =Conditional expression 1?Conditional expression 2? "A" : "B" : "C";
To make a simple table, what kind of movement this will be
Conditional expression 1 | Conditional expression 2 | Output result |
---|---|---|
true | true | A |
true | false | B |
false | false | C |
false | true | C |
I found out when I put it together, but I was confused.
The ternary operator, which has multiple conditional expressions, is completely unfamiliar. I'll put parentheses so that it's easy for me to read.
String str =Conditional expression 1? (Conditional expression 2? "A" : "B") : "C";
This makes it a little easier to see. The next time you see a similar code, put parentheses (in your mind)! I will point out.
After all, it was the easiest to understand if I rewrote it with an if ~ else statement.
String str = "";
if (Conditional expression 1) {
if (Conditional expression 2) {
str = "A";
} else {
str = "B";
}
} else {
str = "C";
}
If you express it with if ~ else, the number of lines will inevitably increase. So, I feel that the ternary operator can be written smarter.
This is the method taught in the comments. Try inserting line breaks instead of parentheses.
String str =Conditional expression 1
?Conditional expression 2? "A" : "B"
: "C";
It is common to write the ternary operator on one line, but it may be better to express it on multiple lines only when there are multiple conditions. I think it's easier to see than the parentheses. * It's just a personal feeling ...
This is also the method taught in the comments. The conditions have been reviewed to make it easier to see.
String str = !Conditional expression 1? "C" :Conditional expression 2? "A" : "B";
If you break this further,
String str =
!Conditional expression 1? "C"
:Conditional expression 2? "A"
: "B";
It's much easier to read than the first ternary operator and the if ~ else statement.
Recently, I am actively using the ternary operator. If you add a lambda expression or Stream API to it, you can express it with a fairly small number of lines, so I like it a lot.
However, if you use only ternary operators during code review, you will be asked "Isn't it low readability?" What should I do ...
Recommended Posts