Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is clearer form: if(!value) or if(flag == value)?

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 preference for one form over the other.

Obviously, the best answer is "refactor the code so you don't need to test for falsehood" but sometimes there's no easy way to do so and the "else" branch is simply to continue processing. So when you must have an "if not false" construct, which is the preferred standard:

The not operator

if (!value) 

Or the test for false

if (value == false) 
like image 615
CodexArcanum Avatar asked Jun 04 '10 19:06

CodexArcanum


2 Answers

if (!value) is easier/faster to follow. Subjective as you said. As long as you are consistent, this is the main thing.

EDIT

One other point to add - omitting the true/false keywords should also (hopefully) force the coder to use better named variables. Bool variables should always indicate meaning or state purpose, such as:

if (MyWallet.IsEmpty)

There is no reason with the above to use == false or == true as it's redundant. The above is human readable immediately.

Far better than having to decipher:

if (MyWallet.EmptyStatus == true) or something ridiculous like this.

like image 99
KP. Avatar answered Oct 13 '22 07:10

KP.


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)

But seriously, and I just thought of adding this, creating appropriate and meaningful variable Names is the key to this issue. You can easily, in the class where value is declared, add a computed variable as in (say "value "is actually "LaunchMissile"),
public bool AbortLaunch => !LaunchMissile,
then all you need is
if (AbortLaunch) ...,
and then it is terse, eminently readable, and avoids the negation operator.

like image 38
Charles Bretana Avatar answered Oct 13 '22 07:10

Charles Bretana