I understand this is a subjective question, so I apologize if it needs to be closed, but I feel like it comes up often enough for me to wonder if there is a general preferen
I personally like
if ((value == false) == true)
...
cause this is verifying that the statement value is false
is actually evaluating to a boolean true...
and, then, obviously, covering both posssibilites adds even more clarity,
if ((value == false) == true && (value == false) != false)
<grin/>
and for those of you who are real gluttons for clarity, and demand incontrovertible readability, I'd suggest
if (((value == false) == true && (value == false) != false) == true)
I don't think it's all that subjective. I have never seen it recommended in the longer form. Actually all the books and coding guides and "How to be a good programmer" HowTos I've read discourage it.
It falls in the same category as
if (value) {
return true;
} else {
return false;
}
OTOH, all the answers given here make my first statement kinda equal not true.
Whatever condition an if
block should evaluate in order to execute must evaluate to true
.
Hence, when value
is false
, the reason why if (!value)
allows an if
block to execute is because the !
operator essentially flips the false
value of value
to true
, thus making the resultant condition within the parentheses evaluate into a true
one that an if
block needs in order to execute.
if (value)
, if (!value)
, if (flag == value)
, if (value == true)
, if (value == false)
, depending on what's to be achieved, are valid code. E.g. if (value == true)
is very useful when value
is a nullable boolean, because if (value)
will give a syntax error, and if (value.Value == true)
will throw exception if you didn't ensure that value
is not null before the if
block is executed.
I would never use if(value == true)
, so just for consistency I would also not use if(value != false)
.
I prefer the second option, the if (value == false)
one.
I gladly use if (~value)
or if (not value)
in languages that support it, but that !
just merges waaaaay too easily either with the variable name or opening braces or | or || operators... at least in my opinion.
Also, two things:
if (value == true)
, and I'm aware I'm inconsistent. And although consistency is very important in my opinion, that pesky !
is simply worse.if(!value)
is clearer and more "elegant", specially if you name boolean variables correctly
Something like
if (Page.IsPostback == true)
seems redundant to me