Skip to content

avoid_self_compare

v1.0.0 Warning Code Quality

This rule flags a.compareTo(a), where the receiver and the argument are the same expression, so the result is always 0.

This rule is in the core preset.

A comparison that always answers 0 decides nothing. A sort built on it leaves the list in its original order, and a conditional guarded by it always takes the same branch — quietly, with no error to trace back to.

It is nearly always a typo. The wrong name gets picked out of an autocomplete list, or a compareTo is left half-edited after a field is renamed. The code compiles and the types check, so nothing else catches it.

Only receivers and arguments that are safe to evaluate twice are compared. next().compareTo(next()) reads the same but calls twice, and a hand-written getter can report a moving value, so both are left alone.

The operator form of this mistake (a == a, a < a) is reported by avoid_equal_expressions, so the two rules never report the same line.

See also: Comparable.compareTo

// Always 0 — the list keeps its original order.
people.sort((a, b) => a.surname.compareTo(a.surname));
if (current.compareTo(current) > 0) {
// unreachable
}
people.sort((a, b) => a.surname.compareTo(b.surname));
if (current.compareTo(previous) > 0) {
advance();
}

To disable this rule:

many_lints.yaml
rules:
avoid_self_compare: false

To keep the rule on but skip certain paths, use per-rule exclude.