I want to use named parameters in Dart for clarity. How should I handle them?

Kafeaulait picture Kafeaulait · Apr 11, 2018 · Viewed 21.1k times · Source

TL;DR: Named parameters are optional as a result of a conscious design choice. Short of having official language support, is there any way to enforce (and inform) required named arguments?


I find it extremely useful to use named parameters when defining a class. Take, for instance, an Ability in an MMORPG:

class Ability {

  final name;
  final effectDuration;
  final recast;            // wait time until next use
  // ...
}

effectDuration and recast both carry the same type of information (i.e. duration of time) and are likely represented by the same datatype. It is easy to mix up which number goes where. However, they are both information vital to the correctness of the object, so they can't be missing during instantiation.

I could just break the program via a try-catch to enforce the requirement of those parameters, but that doesn't sound like fun for someone who uses the class and has no idea (short of reading the docs and understanding intuitively what the class does) that they are required.

Is there any way to enforce the requirement of certain named parameters while managing to inform the caller of said requirement and/or help them use it correctly?

Answer

Günter Zöchbauer picture Günter Zöchbauer · Apr 11, 2018

The meta package provides a @required annotation that is supported by the DartAnalyzer.

Flutter uses this a lot and provides @required directly from import 'package:flutter/foundation.dart'

foo({@required String name}) {...}

foo(); // results in static warning

@required doesn't check if the passed value is null or not, only that a value was actually passed on the call site. To check for null you can also use assert() to check for passed values

class Ability {
  Ability(this.name, this.effectDuration, this.recast) : assert(name != null), assert(effectDuration != null), assert(recast != null);
  final name;
  final effectDuration;
  final recast;            // wait time until next use
  // ...
}