Sound Null Safety in Dart

Sound Null Safety in Dart

What the hell does that even mean?

But first - the dart type system

Dart is type safe, which means it uses compile time and runtime checks to ensure the type of value always matches the variables static type

int x = 10;

// The value of the variable should be an integer

int x = 'hello';

// A value of type 'String' can't be assigned to a variable of type 'int'.
// Try changing the type of the variable,
//  or casting the right-hand type to 'int'.

Why do I need it?

Dart has a static code analyzer that runs in the background of your favourite editor and helps you find bugs before you run a single line of code.

Give me an example.

4: void main{
5:   if( true);
6:   
7: }

// Avoid empty statements. dart(empty_statements) [Ln 5, Col12]
// See the `;` on Line 5

Pro Tip: Use Error Lens plugin in vs code to get the errors inline.

You can customize the analyzer to be more strict etc but that is out of scope.

What is soundness?

Soundness ensures that your program can't get into invalid states because of type mismatches. For example, if an expression’s static type is String, at runtime you are guaranteed to only get a string when you evaluate it.

Benefits of Soundness

  • Revealing type-related bugs at compile time.
  • Code Readability
  • More maintainable code.
  • Better ahead of time (AOT) compilation.

Why you should worry about Null Safety ?

Screenshot 2022-07-10 at 10.54.24 PM.png

Over 1 billion exception events were tracked

So the whole point is to avoid it at compile time so that you can sleep peacefully knowing you are protected from the dreaded null related exceptions.

The Null Keyword

Null safety was a key feature of Dart 2.0. It was released as an opt-in for backward compatibility reasons however is the default now.

// Without null safety:
bool isEmpty(String string) => string.length == 0;

main() {
  isEmpty(null);
}

If you run this Dart program without null safety, it throws a NoSuchMethodError exception on the call to .length. The null value is an instance of the Null class, and Null has no “length” getter. Runtime failures suck.

In dart especially, where you write most of the code to be executed on a mobile device it can be really painful for the end users.

Let's look at some examples:

// In null-safe Dart, none of these can ever be null.

var i = 42; // Inferred to be an int.
String name = getFileName();
final b = Foo();

**To indicate that a variable might have the value null, just add ? to its type declaration:

int? aNullableInt = null;

The variables in Dart are non-nullable by default. Unless you explicitly tell Dart that a variable can be null, it’s considered non-nullable.

Next we will look at examples to handle nulls and build a principle around null safety.

Did you find this article valuable?

Support Runtime Terror Blogs ( •̀ᴗ•́ )و ̑̑ by becoming a sponsor. Any amount is appreciated!