Boolean checking in the 'if' condition

后端 未结 10 1981
陌清茗
陌清茗 2020-12-03 07:40

Which one is better Java coding style?

boolean status = true;
if (!status) {
    //do sth
} else {
    //do sth
}

or:

10条回答
  •  时光取名叫无心
    2020-12-03 08:13

    If you look at the alternatives on this page, of course the first option looks better and the second one is just more verbose. But if you are looking through a large class that someone else wrote, that verbosity can make the difference between realizing right away what the conditional is testing or not.

    One of the reasons I moved away from Perl is because it relies so heavily on punctuation, which is much slower to interpret while reading.

    I know I'm outvoted here, but I will almost always side with more explicit code so others can read it more accurately. Then again, I would never use a boolean variable called "status" either. Maybe isSuccess or just success, but "status" being true or false does not mean anything to the casual reader intuitively. As you can tell, I'm very into code readability because I read so much code others have written.

提交回复
热议问题