3 ms·
I'm surprised* there's no mention of Objective-C's behavior when passing messages to nil. Nothing blows up; the message either returns 0 or an empty struct, dep
by niccaluim 11y ago
I'm surprised* there's no mention of Objective-C's behavior when passing messages to nil. Nothing blows up; the message either returns 0 or an empty struct, depending on its return type. In actual practice this can sometimes result in weird behavior, but overall I always thought it was a very humane feature of the language.
*Well, ok, not /that/ surprised, given the year of publication, but Objective-C did at least exist at the time.
- louthy 11y agoThat seems like a bad idea. It potentially moves the failure further away from the cause. It's nearly always better to fail fast and deal with the problem, than propagate. Obviously it'd be even better to not have null at all, or have a null that doesn't claim to honour a contract that it can't fulfil (Option/Maybe type basically). For C# programmers I attempted to help fix the problem[1] (it papers over the cracks): [1] https://github.com/louthy/language-ext https://github.com/louthy/language-ext
- pavlov 11y agoIn Objective-C, you generally don't treat messaging-to-nil as a failure but a common occurrence. It's a different approach to API design, really. I write much more Obj-C than Java, and I'm always kind of surprised going back to Java that null is such a big boogaboo all over the place. Considering how much influence Obj-C had on Java, it's a shame Sun didn't adopt "benevolent nil".
- Retra 11y agoIt seems a little odd to write code intending for it to do nothing. If that isn't a recipe for obfuscation...
- masklinn 11y agoIt fits the tenets of OOP though, you ask an object to perform an operation, the "null" object just ignores the request.
- Retra 11y agoI'm probably full of crap about this. If you wrote "a = b/c" it would be silly to complain that this operation 'does nothing' whenever b == c happens to be true, so by analogy, it's not too farfetched to think it's useless to write code that does nothing when given a null object. On the other hand, multiplication and division are standardized and familiar operations. Object semantics differ for each kind of object, and it may not make sense to allow null objects for everything, and if you need one, you can always implement it later. So it really depends on what you think the tenets of OOP are, and that's not a cut-and-dry question.