Search code examples
dartdart-null-safety

What's better, an empty non-nullable string or a null and nullable string?


Whether to choose a null nullable container or an empty non-nullable container can be settled convincingly.

A similar question appears to be harder to answer using the same argument. Quite likely both options are open.

Hence to answer this question you can take one of three positions.

We are all familiar (in C++, Java, ..) with the notion of a pointer in a linked list. There it is imperative that the pointer be nullable. That's our signal that we've reached the end of the list.

In Dart's syntax, we'd write Item? next. The "pointer" next is then nullable and will point to a sequel. Importantly, if there is none (at the end of the list), the value null is used as a legitimate and very clear semaphore to indicate so.

What about an even easier case, that of a simple String? Is it always clear that an empty non-nullable string is better than a null and nullable string? Is the converse true? The question may very well be opinion based, which is in itself an answer. (But it needs to be argued.) It may well be that one case is better in some circumstances and the other in others.

As usual, it's best to talk over concrete code. Anything else can easily become a waste of time. Here it goes.

Every Employee has a name, but not necessarily a boss. The CEO, at least, doesn't have one.

We then have two options. We could pinch our nose at using String? and minimize its use by writing String boss

class Employee {
  String name;
  String boss;
}

but that means that boss will sometimes be an empty string.

Or we could use String?

class Employee {
  String name;
  String? boss;
}

and pinch our nose at the continuing use of null to signal the lack of a boss.

What's better, an empty non-nullable string or a null and nullable string? Is this a style issue that can be resolved one way or the other?


Solution

  • You should use null to indicate data which is optional so you can have the Dart type system help you making sure you are not going to use the value directly without first checking if the value have been defined.

    It would not be smart to use empty strings since you are going to forget checking for the empty string at some point and get a runtime error (or undefined behavior) in your application which could have been prevented by using a nullable type.

    It should in general be repeated: The use of null is totally fine. Null-safety in Dart has nothing to do with getting rid of null but to keep track of where null is a possible value and helping us making sure to check for null where it matters and only where it is actually a possibility.