Hacker News new | past | comments | ask | show | jobs | submit login

I'll crank up those `null` assignments to non-optional references warnings up to compiler errors. There's really no reason to ship software that doesn't explicitly declare something as nullable.

The `!`'s are always code smells. I hope I can turn them into warnings or build errors.




I wouldn't say they're always code smells. Like they say in the video, a call to the 'myString.IsNullOrEmpty()' extension method is a null check, but there's no way to prove that to the compiler.


I think that's more of a compiler problem then. Also what's missing is the unwrap syntax to easily transform between nullable and non-null references. What you really want is to operate on a non-null version of that reference if it's proven to be non-null, this is really the Achilles heel of this particular implementation. You're still checking for null all over the place, it's just better checked.

    // Unholy mix of Swift and C# syntax ahead!
    if var unwrappedString = wrappedString && unwrappedString != "" {
         unwrappedString.Length();
    }
Where the `if var unwrappedString = wrappedString` part would unwrap the var and return a `bool` at the same time which is `true` if it wasn't `nil`.

Swift's nil-checking / unwrapping syntax is really short and with some clever usage of `map` or `flatMap` you can still have one-liners albeit a bit more verbose - but much more secure.

Example of using map:

    let myTitle = myObject?.title.map { "Item \($0)" } ?? "No title"
This code can't even theoretically crash anymore and doesn't force unwrapping with `!` as a traditional approach would do:

    let myTitle = myObject?.title != nil ? "Item \(myObject!.title!)" : "No title"


You can totally do this in C#, since it has lambdas, and you can use the extension method to add "map" to nullable references of arbitrary types. It also has ??.

The problem is that lambdas aren't free. For something as simple as a null check, the overhead of a lambda is excessive. Zero-cost lambdas are possible, but require a new type of lambda that cannot escape the enclosing scope, all reflected in the type system.


The reason is that you have millions of lines of existing code written with "nullable by default" assumption in effect, and you need to be able to gradually migrate that.


I think ReSharper already warns about a lot of those so if you've followed up on those warnings already you're in a good shape to switch to compiler errors. I don't think it'll take a long time to fix all new warnings even on larger projects. But the gains are huge.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: