Click here to Skip to main content
15,885,209 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
The perfect way to create an if statement with negation is:
if (!myBool)
{
    Do();
}
I strive to write my code without smell and make it more readable. But I barely see the exclamation mark, so such code doesn't satisfy me.

What I have tried:

Although it will not be tolerated, I would like to write
if (myBool == false)
, because unlike others this line is more comfortable for me than previous one.

I do not need neither in
if (myBool == true)
, nor in
if (myBool != true)
, nor in
if ((myBool == false) == true)
, nor another mess. Only just
if (myBool == false)
to avoid an exclamation mark, but according to SonarLint it's not correct.
I also tried to use multiple ! like
if (!!!myBool)
It doesn't fit as well.

Additionally I tried those things:
if ( !myBool)
issue
if (! myBool)
issue

Is there a way to write more elegantly and preferably avoiding ! and without next?
bool myFalseBool = !myBool;
if (myFalseBool)
{
    Do();
}
May it be something like next
if not (myBool) // this example doesn't possible, though
{
    Do();
}
or maybe next?
public const bool NOT = false;
public const bool FALSE = false;

if (NOT == myBool)
{
    Do();
}

if (myBool == FALSE)
{
    Do();
}
What do you think? Have any ideas?
Posted
Updated 14-Jul-22 6:37am
v2
Comments
Richard MacCutchan 4-Oct-21 7:56am    
What is wrong with:
if (myBool == false)

It makes the meaning clear.
RuthWa 4-Oct-21 21:28pm    
I agree, it does (at least for me). But most of people will not, because https://rules.sonarsource.com/csharp/RSPEC-1125.
Richard MacCutchan 5-Oct-21 3:56am    
I am not sure how 'official' that is, but either way it does not matter. What is important is that you code conforms to the rules of the language (i.e. the compiler accepts it), and is readable, especially to those who will maintain it in the future.
Richard Deeming 4-Oct-21 8:01am    
Other options, depending on your C# compiler / language version:
if (myBool is false)
if (myBool is not true)
RuthWa 4-Oct-21 22:02pm    
Cool, I've never seen that before. But is it right? Can you shortly explain what is it? Does it allowed to use such thing not only for nullable boolean, but both "bool" and "bool?" ?

It is probably the best answer.

In my humble opinion,
C#
if (myBool == false) 
//...

it is acceptable.


On the other hand, a better name for 'myBool' variable would be appreciated...
 
Share this answer
 
Comments
RuthWa 4-Oct-21 21:31pm    
Maybe it is acceptable, but
https://rules.sonarsource.com/csharp/RSPEC-1125

So yes, the second option would be appreciated.
Another hat being thrown in the ring. I also like to avoid having exclamation marks (simply personal preference) in the conditions, but also accept that sometimes it's unavoidable. However in some situations consider how you can invert the boolean value before it reaches the condition.

Most of the time your booleans are going to be produced from inline condition statements and method invocations, so you can invert the value at those points.

For example:
C#
var idIsPositive = id > 0;
var accountExists = IsAccount(id);

if (!idIsPositive|| !accountExists) {
  // show an error
}

Could be:
C#
var idIsInvalid = id <= 0;
var accountIsMissing = !IsAccount(id);

if (idIsInvalid || accountIsMissing) {
  // show an error
}

Just make sure that you use really good naming conventions for your variables. Nothing is worse than reading code and the variables don't make sense in the context, even moreso than having reallyLongVariableNamesUnncessarily;
 
Share this answer
 
Comments
jsc42 4-Oct-21 9:33am    
@Chris_Copeland's suggest is good!

If, for some reason (and I cannot think of any time that that is true), you cannot get a name that makes sense; or (as sometimes happens) you need to correct someone else's logic because they got the test the wrong way round, put the false test in parentheses e.g.

if (!(somethingFalse)) // Parentheses highlights the fact that something awkward is going on
doFalseAction;

alternatively, it is (just about) acceptable to do

if (condition)
{
// Nothing to do if condition is true
}
else // Condition is false
doFalseAction():

I have often seen

if (!condition)
doFalseAction();
else
doTrueAction();

If you come across that, invert the code to

if (condition)
doTrueAction();
else
doFalseAction();

Do not skimp on comments. If your code, after careful refactoring, is still not readable, alert the next reader that there is a pitfall to aviod e.g.

// Looking for a missing value
if (!(HasValue(thingBeingTested))) // See if thingBeingTested has not got a value
doNoValueAction(); // thingBeingTested has not got a value
To be honest, all your attempts at "getting round" what you see as a problem are ugly, inefficient, and unnecessary - and would almost certainly fail code reviews everywhere I've seen.
And make your code look "student grade" at the same time!

If you can't "see" the exclamation mark, then increase the font size of your IDE - "!" is quite large and visible compared to ".", ",", "^", and "~" for example, and missing any of them would make your code even harder to read.

C#
if (!int.TryParse(userInput, out qtyOfCheese))
   {
   ...
   }
Is pretty standard code!
 
Share this answer
 
v2
Readability with "if (! mybool)" statement in C#. Is there another way?

If really you can't read code with an '!', you will have big problems reading other's code and samples codes.
You can also try:
C#
if (myBool)
{
    DoTrue();
}
else
{
    DoFalse();
}
 
Share this answer
 
How code reads is more important then how it "looks"

How do you read: (and we mostly read left to right)

if(!IsSuccess)

Left to right as coded:
If not IsSuccess

With human pre-processing, by reading the statement and then adding words:
If IsSuccess is false or If IsSuccess equals false

Compare to

if(IsSuccess is false) or if(IsSuccess == false)

Left to right:
if IsSuccess is false or if IsSuccess equals false

So we end up reading and not interpreting the code using the syntax above

Removing the interpretation step allows our pattern recognition brain to scan once and obtain meaning, resulting in fewer logic errors.

So when I see code like the above I see a developer with tons of experience who writes code that will be read by humans (mostly left to right) -- weighting debugging over looks, and we know we'll spend more resources later debugging or extending where we must trust the original intent is clear, i.e.

The probable intent of

if( IsSuccess is false ) is higher then if(!IsSuccess) because the developer dictated in their head, what was coded left to right
 
Share this answer
 
Comments
RuthWa 6-Oct-22 4:27am    
The thing is i don't like the fact the negation consists in a single thin stick with a dot (i.e. one character named 'exclamation mark'). For me it is difficult to notice, especially when it stands right before 'I' character which has similar form. So it doesn't matter in what direction to read either right to left or left to right or whatever. This way doesn't help me with both code reading and code looking.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900