Hacker News new | ask | show | jobs
by e28eta 3640 days ago
Something I find very interesting about Swift is it's complete reversal of opinion from Objective-C on this topic.

Obj-C basically has the behavior GP wants: call a method on nil (aka: null) and it returns nil/false/0. It's possible to write concise & correct code that relies on this behavior.

Swift turns it into a fatal runtime error, and uses the type system to help prevent it from happening.

I think there's room for both (probably not in the same project though!). A lot of successful projects have been written in Obj-C, and some of them rely on the behavior of nil.

However, it's harder to maintain the code. You have to reason about whether nil is possible and does the code do the right thing, or did the original author forget to consider the possibility? It's really nice when the static type system forces the programmer to be explicit.

Having used both paradigms, I honestly don't know which I'd prefer for JS - especially considering it's lack of static typing. It might depend on whether I was writing application or library code.

1 comments

There is room for both, but it should be explicit in my opinion. Dart for instance has null safe operators

  // not null-safe:
  foo.bar.baz();

  // null-safe:
  foo?.bar?.baz();
If your type system also does null tracking, then you can see where you might have null values and decide to use the null-safe operators.
Swift has the same syntax for its nullable types. It's also conceptually similar to Haskell's monadic bind over the Maybe type, where your example would look like

    foo >>= bar >>= baz
The nice thing about this approach is that (>>=) is not specific to the Maybe type, and can be extended to other data structures, include one that passes along error messages in the "null" type through the sad path if it encounters them. This would be in the (Either a) monad.