Pergunta

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.

Foi útil?

Solução

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.

Outras dicas

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top