Ensuring that all fields are present in constructor parameter list

Viewed 43

Is there a standard Dart-way of making sure that all fields of a class are present in a constructor parameter list?

A very simplified example:

class Message{
  String header;
  String body;
  DateTime sentAt;

  Message(this.header, this.body, this.sentAt);

  Message makeCopy(){
    return Message(header, body, sentAt);
  }
}

Now, a colleague comes along and adds the field String category, but forgets to add it to the constructor - and even worse, to the copy constructor. Is there a way to make the IDE (IntelliJ) issue a warning or error about this missing new field?

I'm thinking something similar to the warning issued when omitting an enum value from a switch-statement.

Or is there at least some way to make IntelliJ issue such a warning?

2 Answers

You will get warnings or errors if you make your fields final, it seems from your class that it would be a good idea anyway.

Now... granted, that only moves that problem to "how do I ensure my colleague makes all new fields final, too".

To do that, you can declare you class @immutable and then analyzers can warn you.

Analyzers:

  • pub.dev/packages/pedantic
  • pub.dev/packages/effective_dart

A possible class declaration:

import 'package:meta/meta.dart';

@immutable
class Message {
  final String header;
  final String body;
  final DateTime sentAt;

  const Message(this.header, this.body, this.sentAt);

  Message makeCopy() {
    return Message(header, body, sentAt);
  }
}

Try adding a new field or removing one from the constructor, you will get errors.

There is only one way but it is in most cases the correct way to go.

You make all fields final and enforce immutability which will lead to a compiler error if the field is not initialized in the constructor.

You can use the dartanalyzer to enforce the following rules or at least generate warnings. https://dart-lang.github.io/linter/lints/prefer_final_fields.html
https://dart-lang.github.io/linter/lints/prefer_const_declarations.html

To get started more easily with dartanalyzer you can look at the pedantic package or my preference lint.

Related