Comparison wrapped in a logical negation

ID

apex.maintainability.inverted_boolean_check

Severity

info

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Readability

Language

Apex

Description

Reports a comparison that is negated as a whole - !(a == b), !(a > b) and the other four relational forms - where the opposite operator says the same thing directly.

Rationale

The reader has to evaluate the comparison and then flip the result, and the ! is one character wide: it disappears next to a parenthesis, which is how a negation gets dropped or added by accident during an edit. Writing the opposite operator removes both problems and makes the condition readable in one pass.

The following code illustrates the pattern detected by this rule:

public class InvertedChecks {

    public void run(Integer a, Integer b, String name) {
        // FLAGGED: Comparison wrapped in a logical negation
        if (!(a == b)) {
            System.debug('different');
        }
        // FLAGGED: Comparison wrapped in a logical negation
        if (!(a > b)) {
            System.debug('not greater');
        }
        // FLAGGED: Comparison wrapped in a logical negation
        Boolean differs = !(name == 'x');
        System.debug(differs);

        if (a != b) {
            System.debug('different');
        }
        if (!name.contains('x')) {
            System.debug('no x');
        }
        if (!(a == b && name == 'x')) {
            System.debug('compound');
        }
    }
}

Remediation

Replace the negated comparison with its opposite operator: !(a == b) becomes a != b, !(a > b) becomes a ⇐ b, and so on. Keep the negation only when it wraps a call or a longer boolean expression, where there is no single opposite operator to use.

Configuration

This detector does not need any configuration.

© 2026 Xygeni. All rights reserved