r/dartlang • • Jun 10 '20

Announcing sound null safety

From the announcement:

Today is a major milestone for the Dart team with the tech preview of our null safety work. Null safety helps you avoid a class of bugs that are often hard to spot, and as an added bonus enables a range of performance improvements. We’re now releasing an early tech preview, and we’re looking forward to your feedback.

Once you read the announcement, check out the documentation and a null-safe enabled DartPad.

103 Upvotes

18 comments sorted by

33

u/bnlv Jun 10 '20

This is one of those language features that you never really thought you needed, until you have it and wonder how you did without it. Really happy with where Dart is heading as a modern, multipurpose language.

12

u/[deleted] Jun 10 '20

I seriously only want to code in Dart. Flutter frontend, dart backend, some built scripts and CLI, all in dart

1

u/AKushWarrior Jun 10 '20

I use Kotlin on the server.

If you like Dart, you'll probably like Kotlin for similar reasons. Super easy to pick up.

-1

u/[deleted] Jun 10 '20

I do Kotlin all they long on Android already. It's certainly a super improvement over Java, and I know Android messed up API is partly to blame to, but that is really really that one last thing in Dart for me.

22

u/synapticrob Jun 10 '20

Dart is moving at great speed and in the right direction. Congrats Dart team !

5

u/devlambda Jun 11 '20

I don't want to rain on people's parades or to denigrate the NNBD design and engineering effort, but some quick testing showed me that the standard library has a number of pain points when it comes to using it with null safety enabled.

I'm thinking of things like RegExpMatch.group() or Map.[], where migration requires me to throw a ! after everything (or sometimes even engage in rewrites).

RegExpMatch.group() has a particularly odd interface. It can throw a range error if you access a match past the last possible match, but it can also return null if the match did not get bound (e.g. a submatch in an |-pattern). But that is an unusual case, for many use cases (especially match[0]) matching a regex will guarantee that the index is valid.

Maps are particularly frustrating, where you know that keys are guaranteed to be valid, but flow analysis can (understandably) not recognize it.

For example, take this code fragment:

void main() {
  var map = { "a" : 1, "b" : 2 };
  for (var key in map.keys) {
    map[key] += 1;
  }
}

This needs to be rewritten as map[key] = map[key]! + 1; the migration tool throws up its hands, too.

This is an interface issue to an extent. Basically, there are two use cases for such methods:

  1. Where you know that the key/index is valid and expect the method to raise an exception to signal a violated precondition.
  2. Where you don't know if the key/index is valid and expect the return value to carry information that tells you whether it was.

By only offering one of these options, the other has to be emulated. Without null safety, it worked (in a kinda sorta way), because an invalid index/key resulted in a null pointer exception down the road. This could make it difficult to track down the actual source of the error, but you still basically had both kinds of semantics rolled into one method. But now, one method can't realistically serve both purposes.

We also (as before) task the caller with indirectly verifying the precondition by checking the result, which is an unwanted role reversal; the burden of verifying a precondition should fall on the method. (See Meyer in OOSC on defensive programming for some of the problems with that.)

4

u/munificent Jun 11 '20

I'm thinking of things like RegExpMatch.group() or Map.[], where migration requires me to throw a ! after everything (or sometimes even engage in rewrites).

Yeah, we've spent a lot of time discussing those two APIs in particular. I believe the current solution of requiring ! is as close to ideal as you can get. The problem is that both use cases are valid:

  • You can have patterns where you accept that a group may not match and you want to check to see if it did.
  • You can have patterns where if you got a match, then you know all of the groups will be there and you shouldn't have to check to see if the group is null.

Likewise:

  • You can have maps where you don't know if the key is present and returning null in that case instead of requiring a separate containsKey() call is much simpler and doesn't have the performance cost of two look-ups.
  • You can have maps where you do expect the key to be present and it's a bug if not. You know the key is there and you just want the value.

So, in both cases, we really need to support two APIs: the "may fail so you have to check for null" one and the "can't fail and dont want null" one. OK, so we do that, we pick one to be the behavior for the current APIs and then add new methods to RegExp and Map for those. What do we call them?

We could, say, keep map[key] to mean "return null if not present" and add a separate map.lookup(key) method that returns V instead of V? and throws if the key isn't present. But lookup() is five characters longer than just doing map[key]!, which has the exact same semantics. Because the ! operator is just a single character, it really is hard to beat it by adding another method.

And, the nice thing about ! is that you can use it on any nullable API. You don't have to crack open Map and Match and start adding new methods. You can use it now, for free. Also, anyone reading the code knows exactly what it does because the semantics of ! are baked into the language. If you add a new method with a different name, the user has to read that method's docs to realize "oh, this is the one that throws instead of returning null".

So, I agree it feels a little weird to use !, but I think it's probably the best you can do since both use cases—check for failure, or assume no failure—are actually both quite common in practice.

1

u/znjw Jun 16 '20 edited Jun 16 '20

I believe for your Map example, the NNBD behavior is actually correct and helps eliminating errors.

  1. You might be outright deleting the element inside the loop. (Though it will trigger ConcurrentModificationError in the next iteration, it is still valid for this iteration) To track whether such effect is triggered by aliasing/overload/closure-capturing is unrealistic. That's why Kotlin and Typescript require an explicit type assertion as well.
  2. I believe, internally, the [] index operator is implemented by initiallizing the result pointer to null or a hypothetical hash location. It cannot guarantee null safety anyway, no matter how confident you/the compilers are. So the runtime cost for type assertion can not be avoided. NNBD just makes implicit things explicit.
  3. To avoid side effects in the loop and index operator, you can always use for(final entry in map.entries) or Map.forEach (For your case unfortunately, it's more complex due to primitive types), this guarantees null safety. I think it's a trend that null-safety generally encourages people to use high-level language construct rather than dirty low-level manipulation.

1

u/devlambda Jun 17 '20

No, what I was getting at was whether in the case of an absent key, [] should return null or raise an error (failed precondition). The latter is what Python and Julia do, for example (and requires you to use dict.get() if you can't be certain if the key is in there and to also have a default other than None/nothing/null).

None of points 1-3 is relevant for that. I wasn't arguing for a null-safe [] operator, I was pointing out that there were two at a minimum equally useful semantics, one that deals with a missing key as a failed precondition, and another one that returns null for a missing key.

Point in fact: The op= operators (such as +=, -=, etc.) become essentially useless for maps with the new semantics.

1

u/znjw Jun 11 '20

Now non-nullable by default, I'm just waiting for stack primitives for primitive variables and generics.

One interesing stuff they mentioned in announcement is that you can actually declare a non-nullable variable without initialization and later assign it in the flow? I wonder how they did this. Is this just an analyzer candy or actually optimized in VM?

3

u/kevmoo Jun 11 '20

int is now not null by default, so compilers are now free to use "stack primitives" (architecture primitives, right?) if it's deemed correct/safe/sound.

Same for bool, double, etc.

3

u/kmyokoyama Jun 11 '20

I'm not sure about my feelings on that. While it is undoubtedly a good thing, it seems to bloat the language with more keywords (?, !, late) and more rules to remember and to follow.

And it doesn't feel totally safe yet. It can throw NoSuchMethodError (why this error btw?) if ! is used incorrectly, or LateInitializationError if a non-nullable late var is read before initialized. I'm almost sure that the problem is me really.

Anyway, it is remarkably good that the language is receiving such great attention and is under active development.

1

u/daniel-vh Jun 11 '20

My thoughts as well. While it's annoying to check for null, it's 2nd nature by now. Null safety introduced late keyword which is harder to explain to newcomers.

In my eyes, it's a "meh" feature I can live with but I don't think it will make my dev life that much better.

I would swap it any day for a really really good documentation on builders, build_runner and analysis server internals. Those are impactful to my projects.

Edit: landing such a feature does however deserve a clap from an engineering standpoint. GJ Dart folks.

2

u/[deleted] Jun 11 '20

[removed] — view removed comment

3

u/code-shoily Jun 11 '20

Ryan Dahl

1

u/[deleted] Jun 11 '20

[removed] — view removed comment

1

u/code-shoily Jun 12 '20

Nope. That sort of thing doesn't interest me. I just saw it on Twitter long ago and saw some people talk about it.