What is the Java ?: operator called and what does it do?

前端 未结 16 1711
轮回少年
轮回少年 2020-11-21 05:27

I have been working with Java a couple of years, but up until recently I haven\'t run across this construct:

int count = isHere ? getHereCount(index) : getAw         


        
16条回答
  •  说谎
    说谎 (楼主)
    2020-11-21 06:16

    I happen to really like this operator, but the reader should be taken into consideration.

    You always have to balance code compactness with the time spent reading it, and in that it has some pretty severe flaws.

    First of all, there is the Original Asker's case. He just spent an hour posting about it and reading the responses. How longer would it have taken the author to write every ?: as an if/then throughout the course of his entire life. Not an hour to be sure.

    Secondly, in C-like languages, you get in the habit of simply knowing that conditionals are the first thing in the line. I noticed this when I was using Ruby and came across lines like:

    callMethodWhatever(Long + Expression + with + syntax) if conditional
    

    If I was a long time Ruby user I probably wouldn't have had a problem with this line, but coming from C, when you see "callMethodWhatever" as the first thing in the line, you expect it to be executed. The ?: is less cryptic, but still unusual enough as to throw a reader off.

    The advantage, however, is a really cool feeling in your tummy when you can write a 3-line if statement in the space of 1 of the lines. Can't deny that :) But honestly, not necessarily more readable by 90% of the people out there simply because of its' rarity.

    When it is truly an assignment based on a Boolean and values I don't have a problem with it, but it can easily be abused.

提交回复
热议问题