Function parameter is assigned a new value inside the body
ID |
dart.correctness.avoid_reassigning_parameters |
Severity |
info |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Mutable State |
Language |
Dart |
Description
Reports a function or method that assigns to one of its own parameters - a plain assignment, a compound assignment such as +=, or an increment or decrement.
Rationale
The parameter name is the only record of what the caller actually passed. Once it is overwritten, a reader part-way through the body cannot tell whether the name still holds the argument or some derived value, and neither can anyone debugging from a stack trace or a log line that prints it. The habit also hides real defects: a validation or a null check performed on the original value no longer describes what the rest of the body works with, and a parameter reused as a scratch variable will keep working right up to the point where someone adds a second use of the original.
The following code illustrates the pattern detected by this rule:
class Formatter {
// FLAGGED: Function parameter is assigned a new value inside the body
String trimTo(String value, int max) {
value = value.trim();
return value.length > max ? value.substring(0, max) : value;
}
}
Remediation
Copy the value into a local first - var current = value; - and modify that, which leaves the parameter as an accurate record of the call and lets the compiler help by keeping the parameter effectively final. Where the new value is derived once, prefer a final local with a name that says what it is (final trimmed = value.trim();).