Unnecessarily complex Boolean expression¶
ID: cs/simplifiable-boolean-expression
Kind: problem
Security severity:
Severity: recommendation
Precision: high
Tags:
- quality
- maintainability
- readability
Query suites:
- csharp-code-quality.qls
- 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 | Value | |
|---|---|---|
A && false | false | |
A || true | true | |
A ? true : true | true | |
A ? false : false | false |
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.
