dart-lang / linter

Linter for Dart.
https://dart.dev/tools/linter-rules
BSD 3-Clause "New" or "Revised" License
629 stars 170 forks source link

Require all parameters define in constructor in `copyWith` #2939

Open jdebecka opened 3 years ago

jdebecka commented 3 years ago

Describe the rule you'd like to see implemented

Check if all the parameters from the default constructor are included in the copyWith method. There's currently a bug in the TextStyle class where the package parameter can't be passed to the copyWith method which causes an issue when the theme is defined in a separate package.

This method should have the ability to change all the parameters defined in a class and create a copy of an object with not null passed params and keep all the other properties the same.

Examples

class Person {
  const Person({
    required this.name,
    required this.surname,
  });

  final String name;
  final String surname;

  Person copyWith({String? name}) {
    return Person(
      name: name ?? this.name,
      surname: surname,
    );
  }
}

Additional context

Issue Related

pq commented 3 years ago

/fyi @HansMuller @goderbauer @jacob314

HansMuller commented 3 years ago

That's an excellent rule of thumb, although there are exceptions like ThemeData. Ideally, defining a conventional const class like Person, with copyWith, hashCode, operator == etc methods, would be regularized by using a macro definition rather than post-facto analysis.

pq commented 3 years ago

... would be regularized by using a macro definition rather than post-facto analysis

Ah! That's an interesting insight. (fyi @jakemac53 whos' working the static metaprogramming.) Looking at the language feature doc, I notice that this might actually even be a motivating example!

jakemac53 commented 3 years ago

Yes, any use case where a method signature and/or body needs to do something for every field in a class (or a subset matching some criteria) is probably the primary motivating use case for macros. Not only are they generally pure boilerplate code, but they are hard to keep up to date and are a source of bugs.

incendial commented 1 year ago

While we're still waiting for the metaprogramming, this rule is available in DCM https://dcm.dev/docs/rules/common/avoid-incomplete-copy-with/.