Do you avoid Double-Negative Conditionals in if-statements?

Updated by Brady Stroud [SSW] 1 year ago. See history

123

Try to avoid Double-Negative Conditionals in if-statements. Double negative conditionals are difficult to read because developers have to evaluate which is the positive state of two negatives. So always try to make a single positive when you write if-statement.

if (!IsValid)
{
       // handle error
}
else
{
       // handle success
}

❌ Figure: Figure: Bad example

if (IsValid)
{
       // handle success
}
else
{
       // handle error
}

✅ Figure: Figure: Good example

if (!IsValid)
{
       // handle error
}

✅ Figure: Figure: Another good example

Use pattern matching for boolean evaluations to make your code even more readable!

if (IsValid is false)
{
       // handle error
}

✅ Figure: Figure: Even better

acknowledgements
related rules