Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking for null?

Tags:

dart

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?

like image 685
ronag Avatar asked Dec 09 '13 09:12

ronag


People also ask

Why do we check for null?

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.

Is it good practice to check for null?

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.

What is null check in Java?

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.

Why null == undefined is true?

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 ...


1 Answers

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

like image 131
Florent Avatar answered Sep 23 '22 01:09

Florent