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

CodexArcanum picture CodexArcanum · Jun 4, 2010 · Viewed 19.5k times · Source

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)

Answer

KP. picture KP. · Jun 4, 2010

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.