Skip to content

match_getter_setter_field_names

v1.0.0WarningCode Quality

This rule flags a getter and setter pair that does not read and write the same backing field.

This is the copy-paste bug that type checking cannot catch: both members compile, both have the right signature, and the mismatch only shows up as a value that will not stick. It is most common where a class has several similar pairs, which is exactly where it is hardest to spot by reading.

This rule is in the recommended preset.

A settings object with four near-identical pairs — the third one was pasted and half-edited:

class LayoutSettings {
double _paddingTop = 0;
double _paddingBottom = 0;
double _marginTop = 0;
double _marginBottom = 0;
double get paddingTop => _paddingTop;
set paddingTop(double value) => _paddingTop = value;
double get paddingBottom => _paddingBottom;
set paddingBottom(double value) => _paddingBottom = value;
double get marginTop => _marginTop;
set marginTop(double value) => _marginBottom = value; // writes the wrong field
double get marginBottom => _marginBottom;
set marginBottom(double value) => _marginBottom = value;
}
class LayoutSettings {
double _marginTop = 0;
double _marginBottom = 0;
double get marginTop => _marginTop;
set marginTop(double value) => _marginTop = value;
double get marginBottom => _marginBottom;
set marginBottom(double value) => _marginBottom = value;
}

The rule reads pairs in classes, mixins and extension types alike.

Only a pair whose bodies are a single field reference is compared, so several deliberate shapes are skipped rather than guessed at:

class Temperature {
double _celsius = 0;
double _fahrenheit = 0;
// Skipped: the getter computes, so there is no single field to compare.
double get celsius => (_fahrenheit - 32) / 1.8;
set celsius(double value) => _fahrenheit = value * 1.8 + 32;
// Skipped: the setter runs more than one statement.
double get fahrenheit => _fahrenheit;
set fahrenheit(double value) {
assert(value > -459.67);
_fahrenheit = value;
}
}

A compound assignment (+=, ??=) reads the field too, so its asymmetry with the getter can be deliberate and is skipped as well. A getter with no matching setter, or the reverse, is never reported — there is nothing to compare it against.

This rule is on with preset: recommended or preset: opinionated.

To disable this rule:

many_lints.yaml
rules:
match_getter_setter_field_names: false

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