NLemay
NLemay

Reputation: 2383

Good practice : compare a value with a boolean?

Most of the time, I prefer to write this :

if(isWelcome() == true){}
if(isWelcome() == false){}

instead of this

if(isWelcome()){}
if(!isWelcome()){}

Because I feel that it is easier to read (but I do understand that it doesn't make sense).

I would like to know if there is a common agreement about this practice. What most developer do? And I'm wondering if the compiler is doing the extra comparaison, or if it understand that it is useless.

Upvotes: 0

Views: 60

Answers (2)

ryan0
ryan0

Reputation: 1525

Readability is important, and adding words does not always improve readability. While this

if(isWelcome() == false){}

may be more readable than this

if(!isWelcome()){}

for someone who is not familiar with what ! does, this

if(isWelcome()){}

is actually more readable than this

if(isWelcome() == true){}

because now you've introduced "noise words" that are of no informational value, and add to the area your eyes need to scan to understand what's going on. You should strive for minimal code that fully conveys the programmer's intent.

To actually answer your question, I will say that most programmers would use the shorter version. Inexperienced programmers tend to use the "verbose" version.

Upvotes: 1

Lews Therin
Lews Therin

Reputation: 10995

If you use a tool like Resharper you get a hint that it is redundant to use isWelcome() == true. The compiler can choose to optimize the comparison so I wouldn't worry too much about it.

Upvotes: 1

Related Questions