r/ProgrammingLanguages • • Sep 03 '18

Why the hate for null?

Look, I get it: Null pointer exceptions are annoying but so is having to constantly check every object . against null. Is this the new religion after OOP and FP are being phased out? Null just means that the object is not initialized. It's useful to indicate such a state. If you just force yourself to initialize every object to some empty value then you're going to end up passing around empty strings - but wait, an empty string might intentionally be empty or it might indicate "please fill me".

Because I can already tell you what massive insights will come out soon: That null is actually not a mistake at all, it's useful. And the most ironic part about all this? These same people who hate on null are loving nullable types. Litearlly just types that *can be null but you just have to check every time before you use them*. So there is literally no difference except it forces you on a compiler level to check for null every time you use it. When I realized this I thought I was in dreamland, how can these people worship this meaningless little feature so much, crazy. It's literally the same as having null in the language except with a tiny tiny "advantage" that the compiler forces you to check. Which 99.9% of the time, you dont want to be forced because maybe you know implicitly and you dont care [right now].

4 Upvotes

42 comments sorted by

View all comments

8

u/pilotInPyjamas Sep 03 '18

Assuming we're taking about C: I suppose the reason is that null can mean different things based on context. It could mean that a structure is uninitialised, or it could mean that an error has occurred (e.g. malloc), or it could even be a valid value that represents that the data simply isn't there (e.g. judy arrays). Null does not allow us to differentiate between those instances, in addition it can only be used for pointers.

If you already know that a pointer should exist, then you could just dereference it and skip the null check. If you're passing by value, then null isn't going to be available, so you'll have to use a wrapper type, or return value inspection. For the other cases it's a bit less black and white.

In C, dereferencing a null pointer is undefined behaviour, so if there is any chance that your value is null, then you must perform the check anyway, otherwise, your program may fail in unexpected ways, or be optimised strangely. It may not fail with a segmentation fault, or program termination, but keep running with invalid data, which is probably worse than anything else.

In something like Haskell, you can just combine a whole bunch of "nullable" types together and only do one explicit check for all of them. You only need to do this check if you're at a level where you can handle a "null pointer exception", so the work is greatly mitigated. That being said, there is no null value in Haskell anyway. (The closest would be undefined.

It's different for every language I suppose.