Unnecessarily complex Boolean expression¶
ID: cs/simplifiable-boolean-expression
Kind: problem
Security severity:
Severity: recommendation
Precision: high
Tags:
- readability
- maintainability
Query suites:
- csharp-security-and-quality.qls
Click to see the query in the CodeQL repository
There are a number of Boolean expression patterns that can easily be rewritten to make them simpler. Boolean expressions involving comparisons with Boolean literals, ternary conditionals with a Boolean literal as one of the results, double negations, or negated comparisons can all be changed to equivalent and simpler expressions.
Recommendation¶
If A
and B
are expressions of Boolean type, you can simplify them using the rewrites shown below.
Expression | Simplified expression | |
---|---|---|
A == true | A | |
A != false | A | |
A == false | !A | |
A != true | !A | |
A ? true : B | A || B | |
A ? B : false | A && B | |
A ? B : true | !A || B | |
A ? false : B | !A && B | |
A ? true : false | A | |
A ? false : true | !A | |
!!A | A | |
A && true | A | |
A || false | A |
Expression | Value | |
---|---|---|
A && false | false | |
A || true | true | |
A ? true : true | true | |
A ? false : false | false |
Expression | Simplified expression | |
---|---|---|
!(A == B) | A != B | |
!(A != B) | A == B | |
!(A < B) | A >= B | |
!(A > B) | A <= B | |
!(A <= B) | A > B | |
!(A >= B) | A < B |
Example¶
In the following example, the properties Espresso
, Latte
, and Grande
are written in a complex way and can be simplified.
class Bad
{
int Size { get; set; }
bool Espresso => !(Size > 4);
bool Latte => Espresso == false && Size <= 8;
bool Grande => Espresso == false ? Latte != true : false;
}
The code below shows the same logic expressed in a simpler and more readable way.
class Good
{
int Size { get; set; }
bool Espresso => Size <= 4;
bool Latte => !Espresso && Size <= 8;
bool Grande => !Espresso && !Latte;
}
References¶
Microsoft C# Reference: ! Operator, == Operator, != Operator, && Operator, || Operator, ?: Operator, < Operator.