Search code examples
dartnull-checknull-coalescing

Missing Dart null checking shorthand?


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.


Solution

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