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.
Why use this rule
Section titled “Why use this rule”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();}Turning this rule off
Section titled “Turning this rule off”To disable this rule:
rules: avoid_self_compare: falseTo keep the rule on but skip certain paths, use per-rule exclude.
Related rules
Section titled “Related rules”avoid_equal_expressions— Both operands of a binary expression should not be identical.avoid_constant_conditions— Detect comparisons where both sides are constants.avoid_contradictory_expressions— Detect logical AND conditions that always evaluate to false.avoid_accessing_other_classes_private_members— Make the underscore mean what everyone reads it as.