91 points · by ingve · 4y ago · 151 comments
You can literally never trust anything - ever - is not nil because `nonnull` is just a hint, and messaging nil will never crash. It'll just return 0 (or {0} or 0.0 depending on context), which is sometimes valid - and sometimes a horrible failure mode. Failing silently like that is the worst option.
As such you end up having a ton of boilerplate all over the place checking the validity of input parameters to methods and initializers for conditions which shouldn't be representable in the first place - even when the method signature warrants that it's not representable, because it still won't crash on ya.
Let's say you have a chain of property accessors, a.b.c.d, the where d is a float. They're all supposed to be nonnull. You get 0.0. Is that valid? Shrugasaurus rex. Time for the ol' NSParameterAssert(a.b.c != nil).
[edit] Also, canonically, there's 5+1 'null' values: nil, Nil, NULL, -[NSNull null] and 0 - plus nullptr in Objective-C++.
> As such you end up having a ton of boilerplate all over the place checking the validity of input parameters to methods and initializers for conditions which shouldn't be representable in the first place
Dynamically typed languages (at least, JavaScript and Python) have been gradually learning this lesson.
It is far easier to debug a error caused by out of bounds memory writing/reading in python then it is in a strictly typed language like C++.
This is because C++ doesn't actually fail hard and fast when you do this.
If you ever programmed extensively in both languages you will actually see that python is by far less error prone then C++ despite being untyped. Javascript is actually the same, though a little worse then python because how an undefined can get propagated deep into a program.
Still even though an undefined is hard to debug in javascript, it's still traceable through a step by step methodology. A C++ seg fault is not always so straight forward.
I would argue that it doesn't depend on whether the language is dynamically typed, but more on the traceability of crashes.
Yes, Python is safer than C++. C++ makes no pretence of being a safe language. Static typing is not the same thing as safety.
> It is far easier to debug a error caused by out of bounds memory writing/reading in python then it is in a strictly typed language like C++. This is because C++ doesn't actually fail hard and fast when you do this.
Out-of-bounds array access is undefined behaviour in C++, but that isn't a result of C++ being statically typed. If you want a statically typed language with bounds-checked arrays, look at Java, Ada, or Rust.
More broadly, languages with static type systems aren't precluded from using runtime checks.
> python is by far less error prone then C++ despite being untyped.
Again this doesn't generalise to all statically typed languages.
Also, Python isn't untyped, it's dynamically typed. An untyped language is a language with no concept of type, such as assembly or Forth. [0]
> Javascript is actually the same, though a little worse then python because how an undefined can get propagated deep into a program.
How is JavaScript different from Python here?
> I would argue that it doesn't depend on whether the language is dynamically typed, but more on the traceability of crashes.
I'm not sure I follow, what doesn't depend?
I agree that for a language to score highly on debugging, there's more to it than being statically typed.
[0] https://en.wikipedia.org/wiki/Programming_language#Typed_ver...
Python doesn’t stop until you attempt to use Nil, no different from JS or any other lazy bound language.
You might be conflating null/undefined handling with type coercion, which is very different, and much worse.
Modern JS avoids this issue entirely with destructuring, optional chaining, and default params. You can actually write completely safe Javascript now without using any awkward safety checks.
Optionals without this feature/restriction are actually the same as a null.
if(optional_value.has_value())
if(value != NULL)
Both of the above checks are STILL required or it's an error. Optionals only propagate the null to another method call. There has to be exhaustive pattern matching for this feature to truly shine.[1] https://www.infoq.com/presentations/Null-References-The-Bill...
If your language can’t enforce non-nullable references then you have to worry that your Optional might be null. And if your language can enforce non nullable references then you’re boxing your types for no reason because inside if x != null you could just use x unboxed instead of x.getValue(). The only thing you miss is that None<A> and None<B> are distinct types but Go solved that with a typed nil.
For example Python with mypy is so much more ergonomic.
def foo() -> Optional[int]:
return None if coinflip() else 4
x = foo()
if x is not None:
print(x + 5) # no error
y = x * 2 # error None doesn’t have a __mul__ operator.This is completely backwards, and it's much more basic than ebingdom's explanation. Although, I don't think they're necessarily wrong, but I don't think you need functors specifically or category theory in general to explain this.
When your language allows the presence of null values, then by default you are asserting that null is a member of every type in your language. This means that any value can possibly be null.
When using Optional or Maybe or $My_Language's_Name_for_a_Some_Value_or_No_Value_Type, with a language having a half-decent typechecker, for any potential place where you may have a `Nothing` or what-have-you the typechecker will enforce that you are addressing that.
In a language that doesn't provide the ability to distinguish between null values and anything else via static analysis, you are forced at runtime to explicitly check every possible place that a null value could occur (I have used dynamically-typed languages for the better part of two decades professionally; nobody does this), or you can keep the entire logical structure of your application in your head perfectly such that you know where any nulls could occur and thereby skip writing as much code (no one can do this, and anyone who believes they can is either a junior or a junior) or acknowledge that you are a human and write a bunch of tests to try to mitigate potential failures (you will still have a microservice crash and spend a day or two putting out fires when that null slips through, because something something tests don't prove absence of bugs, thank you Dijkstra).
On the other hand, with a sufficiently sophisticated type system, you are able to write programs that let you flexibly target where optional values are present and where they are not with a minimum of boilerplate, and you never have to worry about this particular--but rather _significant_ when it comes to tolerating incessant firefighting--class of errors at runtime. This is better in every way to null.
Just to contextualize my explanation, I took it as a given that we were talking about the two _safe_ ways to handle missing data: a type system which has a notion of nullable/non-nullable types (e.g., Kotlin) vs. a type system which has Option<T> and no primitive notion of nullability (e.g., Rust).
I thought it was obvious that one would want this to be tracked in the type system _somehow_ (to prevent the billion dollar mistake), and that we were just discussing different approaches to achieving that goal.
No, Optional is actually better than null because it's functorial. That means it obeys some common sense laws that one might intuitively expect. Instead of reciting the functor laws, I'll give you a concrete example.
Consider a `HashMap<K, V>` type with the following API:
get(key: K) -> Option<V>
So, `get` returns `None` if the key is not found in the map. That's the proper API one would expect. It forces the caller to acknowledge the possibility that the key might not be in the map.However, if you try to do that with nulls instead of with Optional, it breaks if the value type is nullable, because nulls don't nest. For example, if your `get` method looks more like this:
get(key: K) -> V?
and you use it with a nullable valuable type like HashMap<String, Int?>, then when the `get` method returns null you have no idea if it's because the value was null or the key was not in the map. Then, every time you want to look something up in the map, you have to first check if it's in the map with a different method and then do your lookup. This is error prone, because if you forget to do the check first, your program now has a silent bug that the type checker does not detect.You might think to yourself, "that's silly, why would I ever want to store nulls in a map?" Well, here's one of many possible use cases: suppose you are using the map as a cache, and you want to cache the fact that something doesn't exist. This is called negative caching, and it's occasionally useful.
Or maybe you're building some generic code (like a collections library) that happens to use hash maps internally. If the hash map's get method uses a nullable type instead of Optional for its result, then it's likely that your library does not work correctly for nullable types, because it's easy to accidentally assume that null indicates that the key was not found in the map. That kind of bug won't be caught by the type checker.
Nulls are bad. Optional is good.
We really need to teach category theory to programmers so people can stop making this mistake which leads to error-prone APIs and code with hidden bugs.
mymap = {
“hello”: “world”
}
print(mymap[“hello”])
There’s no need to handle the None case because it’s impossible. But the type checker can’t figure this one out so we have to write. x = mymap[“hello”]
if x.some:
print(x.unwrap)
Every* language with nulls solves for this. Go returns ok, Python has KeyError. They model the same problem in a different way with different trade-offs, the main one being more ergonomic for the programmer and avoiding having to do the same checks anyway and call .unwrap.unwrap.unwrap.* Java has sinned so I can’t really defend that one.
This is also not clear whether the value is missing because it's not set or because it's set to nothing
You might want
> get(key: K) -> Option<Option<V>>
? But you can do that with nulls too, just a matter of having a box around the value
As someone who has been building on Objective-C for >10 years now... it's horrible. Sure, there's less compiler-yelling-at-you-itis, but the code sample the author gives is almost certainly the single biggest source of bugs in Objective-C codebases.
The inclusion of Optionals in Swift is specifically to, in one fell swoop, eliminate the single largest source of bugs in Obj-C codebases.
I get the appeal of getting the compiler to be less strict and yell at you less for just hacking around - but something you use to write production code needs be very liberal about error detection and yelling at you.
Not to mention the same lack of verbosity is supported in Swift with all of the safeties of optionals:
`if dict?.keys.contains("a")`
Which is both semantically and typographically terser, and makes the intention of the code clear (i.e., "dict" is expected to sometimes be nil)
- (id)thingThatSometimesWorks:(NSError *)error;
You can chain these to your heart's content. The one that fails sets the error and returns nil; following messages are sent to nil which does nothing and a particular characteristic of doing nothing is that it doesn't overwrite the error that was set. So you still get to see the error when the workflow finishes.
As an objective-C programmer, I also have a tool in my toolbox which gives NSNull the same message-swallowing behaviour as nil.
@implementation NSNull(GJLNilReceiver)
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector { return [super methodSignatureForSelector:aSelector] ?: [NSMethodSignature signatureWithObjCTypes:"@@:"]; }
- (void)forwardInvocation:(NSInvocation *)anInvocation { [anInvocation invokeWithTarget:nil]; }
@end
I use this pattern because then I can trust _everything_ in a collection. If an object, even an object that represents emptiness, receives a message, it will handle it and do something, even where that something represents emptiness.
var a : T; // cannot be null
var b : T?; // can be null
a.something; // OK
b.something; // not possible because b could be null
b!!.something; // assert that b is not null, then do the stuff
b?.something; // if b is null, return null, else do the stuff
So, each time you see the "?." you know to take extra care with that statement. On the other hand it's very short and easy to write chains of function calls that could return null which then falls through.
And therein lies the root error which makes this entire blog post misguided.
Trivial (hopefully) question:
Would you rather fix 1 bug that takes 10 minutes to find, or 10 bugs that take 20 seconds each?
Given that 'my code silently just... does.... nothing? That's odd' is tens to perhaps even a hundred times harder to find than 'you assumed this could not be null, right on this very line right here, here is the full stack trace how we got there - it IS null' - NPE is superior to this silent treatment.
That's not to say runtime-only null checking (e.g. java without nullity annotations for example) is the only right answer. Far from it.
But it's superior to leaving a trail of ticking time bombs like this.
In effect, you make a difference choice about the semantic meaning of it.
In Objective C, `nil` means: "A sentinel object that is real, has semantic meaning, and that meaning is that it returns nil for all things". Woe is you if you treat it as "An object that indicates the value is unknown or does not apply (no interaction with it was ever expected)".
In java, `null` means: "A sentinel value that indicates the value is unknown/unset or does not apply - hence any attempt to interact with it will throw an error". Woe is you if you treat it as a sentinel. But less woeful - you simply get an exception pointing at the line where you made the brainfart.
Unfortunately lots of program language ecosystems aren't quite as clear about what nil/null is supposed to actually mean (e.g. java where it's often used as sentinel, and then leads to code littered with `if (x == null || x.isEmpty())` style lines, a clear sign someone is not sticking to a meaning of `null` that works well with that particular language.
The article is about nil, not about that.
And yes, part of it is a kludge.
I think that’s only NSNull, and that, technically, isn’t a language issue, but a library one. As https://nshipster.com/nil/ (which explains all of this) says:
NSNull is used throughout Foundation and other frameworks to skirt around the limitations of collections like NSArray and NSDictionary not being able to contain nil values. You can think of NSNull as effectively boxing the NULL or nil value so that it can be used in collections.
I think a better implementation would use a private singleton NSNull inside the container as a sentinel, so that users of the class could store nil values.
Sounds like Visual Basic of old. We used to refer to the four constants of the apocalypse: null, nothing, missing, and empty.
The brilliance is the nil messaging semantic, it allows you to write concise code with a single error check at the end of appropriate, e.g:
[[[foo bar:wibble] thing:1, thing: 2].wat again]
Without having to have error check after error check after error check.These worked together, that return nil had so little cost on the API, you were able to have more error checks that return nil instead of trying to create some kind of fake value. Because you have so many error returns you have to check a lot if you didn’t have nil messaging.
Our belief of what makes things good language design have changed a tiny bit in the intervening years :)
"It is by far the most problematic part of language design. And it's a single value that -- ha ha ha ha -- that if only that wasn't there, imagine all the problems we wouldn't have, right? If type systems were designed that way. And some type systems are, and some type systems are getting there, but boy, trying to retrofit that on top of a type system that has null in the first place is quite an undertaking." -Anders Hejlsberg
If something can be nil, handle the case. There’s nothing brilliant about objective-C’s nil kludge.
Yes, you need to know what you're doing in any language, the difference is whether those things are due to the language or the problem you're actually trying to solve. The more things in the language you have to keep in mind, the less of your domain problems you have room for.
I'd rather take a crash (that way I'll know soon that I have a bug and it'll be easy to fix) or, even better, a compiler/type error ("code is expecting a fully constructed object but doesn't always receive one").
In C++ I recently started using a NonNull<> templated type (with specializations for std::unique_ptr<> and std::shared_ptr<>): https://github.com/alefore/edge/blob/af1192a70646f662539bfe6...
It's slightly verbose, but has allowed me to delete a ton of CHECK(x != nullptr) statements (since the type will already carry the information that x can't be null) and this use of types has helped me detect a few mismatches (where e.g. the consumer had unnecessary complexity to deal with null but the caller always emitted fully constructed types, or the, much worse, symmetric case).
The correct reasoning would be to recognize that certain language features make entire classes of bugs impossible. For example, in my Rust projects, I never have to worry about null pointer errors. Sure, there might be other types of bugs in my code. But at least I don't have bugs due to nulls. Also, there are no data races in my code—yet another thing I don't have to worry about thanks to the design of the language. (I'm not saying Rust is perfect. I'm just using it as an example.)
Other times, the need to have direct hardware access from the BIOS on up cannot be avoided.
The bugaboo is the quest for the One True System that is all things to all people.
Emacs is as close as we get to that Nirvana.
typedef std::optional maybe;
using nil = std::nullopt;
Not quite the right definition, but I’m on an iPad.When you combine those with an “either” function which returns either a maybe<T> else a default T, you end up with a nice way of having default args in C++. Everything defaults to nil, then you set it to either(foo, defaultFoo()) in the body of the function.
Of course, C++ already has what it calls default arguments. But lisp has corrupted me. The defaults can’t be a function call, and the values can’t refer to other arguments, so they feel useless.
Heckin C++. I feel like programmers 80 years from now will still be yearning for an escape, whereas C++100 will still be the dominant systems programming language. Golang was a nice attempt, and so is Rust, but empirically the evidence is that (at least in AI) you can’t escape C++. The best thing to do is to just dive in.
using nil = std::nullopt;
I don't think that compiles? The right hand side is a value, not a type.Some languages allow you to say “this can never be null”, and in general, i find that really helpful and ergonomic but there’s cases where it’s not practical and you have to permit null and at that point, you’ve sunk the boat.
Strict non-nullable with Option types has been moved to 2nd place solution since i experienced nil punning.
Treat nil as a value, like in this article’s example of the array being terminated by nil. Don’t make it an exception to compare against nil. But don’t ascribe any other meaning to the value - that means no matter the context, nil can semantically fit your use case.
It’s better than option primarily because it means a lot less code. You delete all “is this value present?” type code from your codebase because encountering nil in your happy path is rendered harmless.
Very nice.
Only if by "harmless", you mean "creates a bug later rather than a crash now", as compared to traditional null handling. But Optional has neither problem.
>It’s better than option primarily because it means a lot less code. You delete all “is this value present?” type code from your codebase
"It's better because it's less code" is a pretty big red flag if that's the only advantage. Especially when "less code" means `foo.bar` instead of `foo?.bar`, or `if foo.bar` instead of `if foo?.bar == true` (and even in the second example, if you're touching `foo` multiple times, you can unwrap it one time with `if let` instead).
> It’s better than option primarily because it means a lot less code.
Option doesn't need any extra code for checking the presence of a value when it's done right. In Rust, you just place a ? sigil at the end of the option expression. In Haskell, you just use the do syntax where val <- optional will assign the value to `val` if `optional` is some value rather that none, and it will exit the do block otherwise.
Ahh, those are both logic errors in your code. You do need the extra code to fix your errors here:
>> In Rust, you just place a ? sigil at the end
That changes the behaviour to bubble up that there was no value, the caller has been delegated responsibility and further processing has stopped at this point.
Instead to accurately implement the required behaviour and replicate the nil punning logic, you’d need ? to behave in such a way that it inserts a suitable “empty” value for whatever type the option is guarding. So if this was an optional collection for example, the ? would need to figure out what type of collection then how to get an empty one to provide here (and you’d probably want that to be a singleton immutable collection, otherwise you’d be risking introducing logic bugs).
In practice, you’d instead write code to provide that empty collection at the call site. At this point you’ve rendered the Option wrapper pointless though.
It’s the exact same story for your Haskell example.
You’ve given a different behaviour which is of course, a logic bug.
Some types have no suitable "empty" value. It is dangerous to assume you can always find such a value.
In essence, when you're expecting that such a value exists, you're implicitly relying on your type being a suitable monoid. That's fine when you're expecting this and when it is actually a monoid, but not all types are.
> In practice, you’d instead write code to provide that empty collection at the call site.
Not all types can be modelled as collections. This is the same problem as above.
What I'd actually do is either:
1. Fail the parent operation by again using `?`, or 2. Provide a suitable default/"empty" type, if it is possible to continue.
It's very important that such a decision is explicit on a case-by-case basis, and this is what `?` allows you to easily do without much fluff or noise.
> At this point you’ve rendered the Option wrapper pointless though.
How was it useless? It allowed us to safely write a procedure as if the value existed and otherwise cheaply signal failure to the caller. The caller can then repeat the same process.
What's important is that the procedure stands on its own and is safe out of the box. It clearly says that it can fail (by returning an option) and we know exactly when it has failed and when it has not.
> You’ve given a different behaviour which is of course, a logic bug.
I don't see where the bug is?
If comparing against nil does not fail, you are ascribing the value of "false" to it. If it works in every use case, you are ascribing an arbitrary value to it in every use case.
Specifically to your point about the hard crash, I’m interpreting this as meaning “i want the programmer to be told they’re mistaken”, if I’ve got that right, you’ll be pleasantly surprised.
In Swift, you can call methods on Optional values, and they evaluate to null or the actual value. So the authors example:
if (dict.containsObjectForKey[@"a"]) { ... }
Would look like this:
if dict?.contains("a") { ... }
The `?` tells Swift to only call `contains` if `dict` is not null. The return value of this call would then be another optional. This second point is the improvement over Objective-C. There, you would not know whether the return value of `dict.containsObjectForKey` is a potential null value. This, in turn, would crash the app if you'd try to use this return value to, say index into an array or perform math on it. In Swift, the compiler yells at you to remind you that this value can be null.
So, really, Swift has the same benefits, but better.
`if arr?.contains("a") == true { ... }`
or
`if arr?.contains("a") ?? false { ... }`
or
`if (arr ?? []).contains("a") { ... }`
or
`if let arr= arr, arr.contains("a") { ... }`
or
`if arr!= nil, arr!.contains("a") { ... }`
Optional<Bool> will not automatically unwrap where Bool is expected (since the compiler would have to assume nil is falsey, which is the kind of mushy shenanigans Swift explicitly denies).
[object method]
where method is supposed to return an int, will return 0 if object is nil. This is of course a double-edged sword: it's too easy to make a mistake in your logic, but also you can use it to your advantage if you know what you are doing.The advantage really being just writing slightly less, i.e. eliminating extra if's. All this, however, didn't save Objective-C from being over all a very verbose language. At least from my experience of rewriting from ObjC to Swift, the latter can make your code half the size of the original and as an added bonus will make it so much safer too.
This is why Objective-C is objectively and hopelessly dead now.
Another cool thing is that you can use ?? At end of expression that can return nil to decide what to do if nil is returned (for example return something else). So swift actually reduces the amount of ifs required.
No, it doesn't. (You probably meant object?.mymethod()). If mymethod returns int, then in Swift the result of this expression is strictly Optional<Int>, whereas in Objective-C it's Int defaulting to zero if object is nil. The implications in terms of safety are significant.
huzzah :)
The literal syntax `@[ ... ]` gets transformed into an initializer call, which throws an exception if it is passed a `nil` value. And I can't remember, but I would expect the compiler to at least warn, if not error, if you put a literal `nil` in there.
These both long predate the array and dictionary literal syntax.
If programmers today treated software like a car, they would blow up the car every time the air conditioner button didn't work. Desktop and console apps work this way.
Perfect is the enemy of the good, many times your app isn't running a nuclear reactor, and even if it was you might want it actually be able to recover from a failure. Think Erlang.
Conventional Erlang style is to crash a lot, but to limit the amount that crashes by using enough processes, I believe, c.f. "The How and Why of Fitting Things Together" <https://www.youtube.com/watch?v=ed7A7r6DBsM&t=1535s>. But the key part to handling failure is to detect it first, and silently passing through nil/null/etc is not that.
Is this line the victim of an overeager s/pre/code/g I wonder…
> switdhing to Swift “feels like a Jedi who’s trying to switdh from a lightsaber to a blaster,”
if (dict != nil && dict.containsObjectForKey[@"a"]) { ... }
Can become this:
if (dict.containsObjectForKey[@"a"]) { ... }
This is probably the least-Swift thing ever, but, if you're used to coding in this style, it's fantastic
Why is this better than a language that can guarantee that dict is not null?if foo || bar || baz || you_do_not_even_know_what_comes_next break
or:
retval = foo || bar || baz || you_do_not_even_know_what_comes return retval
&c
I don't understand why it's notable except that it's not really JS or Pythonic . . .
dict.containsObjectForKey[@"a"]
Becomes roughly
dict?.containsObjectForKey(“a”) == true
Also, the author admits there are two kinds of null in Swift, as compared to four in Obj-C. Is the second kind he's referring to `NSNull`? Doesn't that only exist to bridge with Obj-C APIs that haven't been updated yet? That's pretty misleading, if so.
I sort of prefer Swift:
let array = [“a”,”b”]
let dict = ["a":[1],"b":["c"]]
print(type(of:dict["a"]))
=
Optional<Array<Any>>On the other hand, if NULL is not an expected value, then how often do you really find the logic error at the same spot that the panic occurred? Not very often in my experience. We have callstacks for a reason. You usually find the NullPointerException at the bottom of the stacktrace or the None.panic() after 100-something other function calls in significantly complex codebases. No, if a function expects a value 100% of the time, and it was passed a NULL value, that's the caller's problem. And Option<T> won't help you if the user-facing calling code is still passing None or std::nullopt for whatever misguided or erroneous reason they may be doing so.
Certainly I agree there're benefits to encoding this kind of behaviour into the type system, but I don't agree that it's ultimately a solution to the '4 billion dollar mistake', since mistakes ultimately still happen. You just swap NULL for None and you still have a bug in your logic, just no longer a bug in the types. It's kicking the can.
Other things too but I’m too lazy (forgive the clickbait title):
PS: The co-existence of nil, Nil, NULL and NSNull was just unfortunate.
dict.setObjectForKey(@"b", @"a");
assert(dict.containsObjectForKey[@"a"]);
A bit tangential related to the article:In Python, I often found that it is helpful to also have a separate "None"-like type despite None, which I called NotSpecified. Often in functions you have sth like:
def func(opt: int = None):
if opt is None:
opt = get_default_opt()
...
This works fine when you now that opt should not be None here. However, if None is allowed for opt and causes some other specific behavior, I now do: def func(opt: Optional[int] = NotSpecified):
if opt is NotSpecified:
opt = get_default_opt()
...
This is also useful for dicts: my_dict.get("foo", NotSpecified)Maybe.
It's called exhaustive pattern matching on sum types with the Maybe monad (or Optional). I believe Haskell popularized this syntax and Rust and Swift borrowed it from Haskell. Strictly speaking though, haskell pattern matching isn't exhaustive but the compiler will give you a warning if your code doesn't handle every case.
Elm is another language that exploits this feature to a scale where unless you use the FFI, elm programs cannot logically ever crash.
Null solves the problem of missing values, but introduces the problem of undefined behavior. What happens to when you try to divide an integer with NULL? Often times the program just chooses to crash.
To be fair though the problem isn't null itself. It's the failure of null to be incorporated into the type system. Instead null is used as a value to bypass the type system and silently propagate through your program and finally cause an error when you try to do an operation on it.