0

I know that Dart has the null checking shorthands

x = y ?? z;

and

x = y?.z;

But what if I have a statement like

x = (y != null) ? SomeClass(y) : z;

I don't want to pass null to the SomeClass constructor - so in that case I want x to be set to z (in my specific situation z happens to be null).

I can't figure out how/if I can use any of the shorthands in this scenario, or if I'm stuck with the direct null check.

Magnus
  • 17,157
  • 19
  • 104
  • 189

1 Answers1

0

The short answer is: there is no shorthand. Your code is good.

The really short answer is: it depends. ;)

If you think about the surrounding codebase you can come up with a different architecture overall.

You may as well pass null to the constructor

x = SomeClass(y);

and then give a reasonable default in your initializer list:

class SomeClass {
  dynamic _value;

  SomeClass(value) _value = value ?? ''; 
}

or throw an exception:

var nullError = Exception('Null value not allowed');

class SomeClass {
  dynamic _value;

  SomeClass(value) _value = value ?? (throw nullError);
}

though a more idiomatic way would be this:

class SomeClass {
  dynamic _value;

  SomeClass(value) {
    ArgumentError.checkNotNull(value);
    _value = value;
}

As I know nothing about the rest of your code, I cannot give you the right answer. But I suggest you to ask yourself:

  • Where does this z value come from? What is its meaning? (If you're in big project, you may use Dependency Injection or Factories.)

  • Maybe I have a view component, where empty strings are more useful than nulls?

These are some things I would ask myself. But if you're hacking a quick script, this maybe a long shot. You may have already finished your task by now, and maybe you really had no need for a shorthand in the first place.

Spyryto
  • 1,107
  • 12
  • 17
  • That's one long short answer! ;) For this specific task I think the best option is to just keep the direct null check, but your points are good to keep in mind. – Magnus Feb 22 '19 at 10:27
  • The answer was short. But then I elaborated on that :P – Spyryto Mar 07 '19 at 08:50