Hacker News new | ask | show | jobs
by bcherny 3000 days ago
This is a really neat idea, and is a lot more ergonomic than nulls or optionals in JS. Until optional chaining makes its way into the spec [0], this is the cleanest way I’ve seen to operate on maybe-null values.

[0] https://github.com/tc39/proposal-optional-chaining

2 comments

It's also hell to debug as it silently always works and propagate.

It's good for unit testing though.

That’s true, but ostensibly you only use it in places where you expect nulls and don’t intend to debug anything. That’s why Smalltalk, C#, CoffeeScript, and probably JS and TS soon have null chaining.
Objective-C also allows nil to receive messages which then just returns nil also. I’ve always found this really natural in that you can assume something is either valid or null and avoid a whole lot of null checks this way. That said, I’ve never been terribly frustrated by other languages either which throw when calling methods on null. Maybe it’s because of heavy use of certain design patterns that make it so it’s never really a surprise?
It also means a chained call with an nil in it still complete from start to end. So it has additional overhead, and you better not have side effects in there.

All in all, I'd like to have some kind of "?" operator in Python, I do think the pros are most of the time greater than the cons.

Not a new idea, though. It’s basically the venerable Null Object pattern as documented by the Gang of Four book.