Checking for null?

dart

Solution

In Dart's source code they throw `ArgumentError`. Most time they don't check for `null` but the variable type.

int codeUnitAt(int index) {
  if (index is !int) throw new ArgumentError(index);
  // ...

Source: dart/sdk/lib/_internal/lib/js_string.dart#L17

factory JSArray.fixed(int length)  {
  if ((length is !int) || (length < 0)) {
    throw new ArgumentError("Length must be a non-negative integer: $length");
  }
  // ...

Source: dart/sdk/lib/_internal/lib/js_array.dart#L25

Problem

In Dart we have simplified initialization of variables through the constructor: e.g. ``` class Foo { Bar _bar; Foo(this._bar); } ``` At first glance this seems very convenient. But in my experience in 95% of the cases you would expect that what is sent in to a constructor should be non-null. e.g. in C# I would write: ``` public class Foo { private Bar bar; public Foo(Bar bar) { if (bar == null) throw new ArgumentNullException("bar"); this.bar = bar; } } ``` So my question is what the best-practice in Dart for null arguments is? Given that we have a language feature that basically discourages it?

Original source