Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
680 views
in Technique[技术] by (71.8m points)

coding style - Is it bad to explicitly compare against boolean constants e.g. if (b == false) in Java?

Is it bad to write:

if (b == false) //...

while (b != true) //...

Is it always better to instead write:

if (!b) //...

while (!b) //...

Presumably there is no difference in performance (or is there?), but how do you weigh the explicitness, the conciseness, the clarity, the readability, etc between the two?

Update

To limit the subjectivity, I'd also appreciate any quotes from authoritative coding style guidelines over which is always preferable or which to use when.


Note: the variable name b is just used as an example, ala foo and bar.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's not necessarily bad, it's just superfluous. Also, the actual variable name weights a lot. I would prefer for example if (userIsAllowedToLogin) above if (b) or even worse if (flag).

As to the performance concern, the compiler optimizes it away at any way.

Update: as to the authoritative sources, I can't find something explicitly in the Sun Coding Conventions, but at least Checkstyle has a SimplifyBooleanExpression module which would warn about that.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...