Search code examples
if-statementbooleancode-readability

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.


Solution

  • 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.