Check for zero?

In Dart, we simplified the initialization of variables through the constructor:

eg.

class Foo { Bar _bar; Foo(this._bar); } 

At first glance, this seems very convenient. But in my experience, in 95% of cases, you expect that what is sent to the constructor should not be null.

eg. 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 is the best practice in Dart for null arguments? Given that we have a language function that basically scares it away?

+6
source share
4 answers

This initialization method only eliminates the need to manually assign parameters, checks, and other logic still requires a body. In my opinion, a useful feature.

 class Foo { var _bar; Foo(this._bar) { if(this._bar==null) throw new ArgumentError(_bar); } } 
+4
source

In the Dart source code, they throw an ArgumentError .
In most cases, they do not check for null , but the type of the variable.

 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

+4
source

It depends on what you prefer.

The most common code is similar to the C # you are showing:

 if (bar == null) throw new ArgumentError("arg is null"); 

It provides useful error messages and prevents the execution of incorrect code (for example, accidentally formatting hard drives at level zero).

I would write:

 Foo(Bar bar) : this.bar = bar { if (bar == null) throw new ArgumentError(...); } 

because I find it more readable than alternatives, but if you prefer, you can even write:

 Foo(Bar bar) : this.bar = (bar == null) ? throw new ArgumentError(...) : bar; 

Using "assert (bar! = Null)" works great. It only catches the problem in checked mode, but if it's just to protect itself (for example, from the inner class in your library), that's good enough. For public functions and classes, I would prefer if-throw.

+3
source

You can use assert to perform your checks.

Chapter 2. An Overview of the Language of Gifting

 assert(text != null); 

Approval operators work only in validation mode. They do not operate in production mode.

Thus, the statement is convenient for development, but does not affect production productivity.

If you want the validation to be preserved during the production process, you can do it like in C #

 if (bar == null) { throw new ArgumentError('Bar must not be null'); } 

Exceptions - Dart Tips, Ep 9

0
source

All Articles