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?
It is a good idea to check for null explicitly because: You can catch the error earlier. You can provide a more descriptive error message.
You will often want to say "if this is null, do this", and continue executing. Without the null check you won't get that chance, your whole call stack will be unwound and Unity will go on with the next Update() or whatever method it's going to call. Another is that exception handling is not free.
In Java, null is a literal. It is mainly used to assign a null value to a variable. A null value is possible for a string, object, or date and time, etc. We cannot assign a null value to the primitive data types such as int, float, etc.
Summary. undefined is a primitive type of a variable which evaluates falsy, has a typeof() of undefined, and represents a variable that is declared but missing an initial value. null == undefined evaluates as true because they are loosely equal. null === undefined evaluates as false because they are not, in fact, equal ...
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With