It is argued that the ternary operator (? :) increases readability and decreases readability. I find it easy to read, depending on how I write it. Readability is a common story, so I'll write a story about how to actually get it in your head.
When I told my juniors how to write a highly readable ternary operator (language is Java) "I looked it up before and it's certainly easy to see, but when I write it, I forget it. I look it up every time and think about it." So I talked about how I wrote the source when I wrote it. It seems that it was good as it is, so I will write it as an article.
I'm coding like this, but how about everyone?
There are various ways to write it, but as a coding style, for example, it is written like this.
String plan = count > 10 ? "A" :
count > 5 ? "B" :
/* other*/ "C" ;
And
String plan = count > 10 ? "A"
: count > 5 ? "B"
: /* other*/ "C" ;
In the above writing, ":" is at the end of the line, and there is a feeling that "the condition still continues to the next line". I like it, but the writing style I often see is below.
I write while chanting with my head as follows. I'm chanting in parentheses in my head.
Once you get used to it, you will be able to use it naturally. If you repeat coding while chanting about 3 or 4 times, After that, the brain miso spends less time on the grammar of the ternary operator, You will be able to code naturally (I think ...).
(Plan) count> 10 (In the case of?) "A" (···so)
count > 5 (In the case of?) "B" (···so)
(Otherwise)"C" ;
Characters to actually write/Character to read | Words chanted in the head |
---|---|
? | In the case of? |
: | ···so, |
/* other */ | Otherwise, |
Recommended Posts