Provide analyzer support for verifying copyWith
-style implementations.
#5033
Labels
P2
A bug or feature request we're likely to work on
set-recommended
Affects a rule in the recommended Dart rule set
type-enhancement
A request for a change that isn't a bug
type-question
A question about expected behavior or functionality
In the absence of a good way to copy immutable objects with some field changes, the Flutter team often implements a
copyWith
function that copies the original object with optional overrides of individual fields. It's invaluable for being able to work with immutable classes.However, in the implementation, it's really easy to fat finger something and not hook it up correctly, resulting in possible catastrophic bugs. We try to write unit tests to handle this, but sometimes even then the test can miss it if we choose the wrong test.
For instance, an example implementation looks like this:
Can you spot the error? If you're looking for it, it's pretty obvious, but it is easy to miss in a review. (
pointRounding
is being assigned the value ofvalleyRounding
).The
unnecessary_this
analysis warning can sometimes help here if you've renamed a field but not the name of the parameter in thecopyWith
(another common error), but it doesn't catch the case above.Ideally there'd be a general lint that could check all instances of a
copyWith
for these kinds of errors, but I realize that the variation in implementations probably makes that impossible.Are there any good ways to improve the situation? Could we have an annotation that a parameter must be used in the implementation? Could we annotate these kinds of copying functions and force them to conform to a pattern (must accept a parameter with the same name as all public fields, must use all parameters in result, target parameters must match source parameters, etc.)? Could we have a way of auto-generating these copy functions instead of writing them?
I mean, it seems like the best solution is a language solution that lets us describe how to copy an immutable class with changes, but I don't know what that is, and it seems like it might be hard to come up with a good general solution. In the meantime, it would be good to be able to avoid these common errors.
The text was updated successfully, but these errors were encountered: