CodeQL documentation

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.

ExpressionSimplified expression
A == trueA
A != falseA
A == false!A
A != true!A
A ? true : BA || B
A ? B : falseA && B
A ? B : true!A || B
A ? false : B!A && B
A ? true : falseA
A ? false : true!A
!!AA
A && trueA
A || falseA
Some expressions always yield a constant value. If the side-effect in `A` is intended, consider restructuring the code to make this more clear. Otherwise, replace the expression with the constant value as shown below.
ExpressionValue
A && falsefalse
A || truetrue
A ? true : truetrue
A ? false : falsefalse
In addition to the rewrites above, negated comparisons can also be simplified in the following way:
ExpressionSimplified 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

  • © GitHub, Inc.
  • Terms
  • Privacy