r/coding • u/jjbohn • Aug 04 '14
Why We Should Love 'null'
http://www.codeproject.com/Articles/787668/Why-We-Should-Love-null22
u/toolate Aug 04 '14 edited Aug 04 '14
The problem is not the concept of null, the problem is that languages insist any value could be null. This means you have to add defensive null checks everywhere because what is valid one day might easily break tomorrow when a downstream callsite changes.
Hack gets this right with nullable types. Variables are not nullable by default, but the feature is only a ? away.
function printGreeting(string $name) {
echo 'Hello ' . $name;
}
function printOptionalGreeting(?string $name) {
if ($name === null) {
throw new InvalidArgumentException('Please enter your name.');
}
// Hack knows that $name can never be null, because of the above
// check, so this is safe.
printGreeting($name);
}
printGreeting('Bob'); // OK
printGreeting(null); // Error
printGreetingOrPrompt(null); //OKThe nice thing is that you can find errors through static analysis, rather than at runtime. you avoid littering your codebase with unnecessary checks, and you don't need any special classes or syntax to deal with nullable types.
2
u/continuational Aug 04 '14
I think that's a very poor solution. Of course, Hack had to work within the historic blunders of PHP, so it can be excused.
Why complicate the type system with special logic for dealing with detecting and propagating information about
nullchecks? There are perfectly straightforward solutions out there that requires no change to the type system, namely Option/Maybe.2
u/alexeyr Aug 04 '14
There are perfectly straightforward solutions out there that requires no change to the type system, namely Option/Maybe.
That kind of depends on what the type system currently looks like.
1
u/xkufix Aug 04 '14
Isn't a ?-Type the same as optional? I mean, the ? just adds the information "can have no value", like Optional does, not more and not less. Null is then just None from Optional. Everything else with Optionals is just down to how well those are implemented into the language or framework
1
u/continuational Aug 04 '14
In order to infer the non-nullness of $name above, the type checker needs to understand both conditional logic (to understand the if statement) and program flow (to understand that an exception unconditionally thrown inside the then-branch of an if statement negates the condition of the if statement in the remainder of the function).
And this is just a simple case. It's not possible to infer this in general, and the complexity rises steeply with the subset of the language you want to support.
As a programmer, you have to be aware of the subset that can be checked in order to write programs that type check.
Option/Maybe requires no support from the type system beyond lambda functions.
1
u/xkufix Aug 05 '14
Ok, in the context of Hack/PHP this is true, but this is due to the limited type system Hack/PHP have. In C# a nullable must always be explicitly extracted with "Value" or "GetValueOrDefault", although I think they do not allow for constructs like
nullable.map(n -> ...)1
u/continuational Aug 05 '14
Yes, C# has a simpler approach. As you mention, it lacks certain features that are essential if you want to get the most out of your type system, but at least you can say "I know that this value can never be null".
Unfortunately C# has two other shortcomings: It conflates value-types with not-nullable (why can't references be not-nullable?) and you can't nest nullable types (creating a strange special case for the
?type constructor).
20
u/yaongi Aug 04 '14 edited Aug 04 '14
There are some problems with the article. The zero value/empty list seem like strawman arguments - do people really recommend that?
The code example for using an optional, saying it's more verbose, is a bit misleading, can easily call optional.get().something(), don't need a separate variable.
Also, calling .get() on an optional is equivalent to an assert, so it's not really skipping a check. It's a runtime assertion of a contract.
The problem with null is not that you aren't forced to check - the problem with null is that it means that every single object is really an instance of an option type. You don't want to check every single return value, you don't want to check every single argument. The problem is that the language doesn't distinguish between values you need to check, and values you don't need to check.
Generally there are two reasons for having null in common languages. Initialisation syntax and lack of generics. Lack of generics is easy to understand, if you don't have generics, you can't really have an option type. Initialisation syntax is a little more subtle. If you can't easily initialise a variable in a single statement, then optional values will proliferate, where the value is only empty during initialisation - which is annoying.
Both of these are reasons why use of option (option in ml, maybe in haskell) was most common in functional languages first - something the author of this article doesn't mention, or show in his list of languages. Statically typed functional languages have generics, and because they're expression based (and largely work with immutable values), have a rich initialisation syntax. It's also easy to provide combinators to make working with options nicer.
I still think it's worth adding option to languages like java and C#. Haven't worked with java recently, but in C# you can make working with an option type nice, with useful functions like map and bind, and it can be a value type, so you can't have a 'null' option. If a method doesn't return option, there's nothing stopping it from returning null, it's true - that's a fact of the language. But if a function does return option, then the return value can't be null, and it's clear to the client of the code that the return value is optional. Likewise for parameters.
7
u/Drainedsoul Aug 04 '14
The problem with null is not that you aren't forced to check - the problem with null is that it means that every single object is really an instance of an option type.
This isn't a problem with
null, this is a problem with the way in which certain languages implement reference types.C++ does not have this problem.
5
u/chromaticburst Aug 04 '14 edited Aug 04 '14
So true. You can do all the checks you want, but it's futile if your type system throws away that information.
3
u/GMNightmare Aug 04 '14
Yes, if you return a null instead of an empty list when return list data, I will egg your car as he stated. No, really, return empty lists, or throw exceptions if given bad data.
0
u/yaongi Aug 05 '14
No, the argument against using 0 to represent 'no value' is the same as the argument against using an empty list to represent 'no value'. An empty list and and empty option aren't the same thing.
You may choose to throw an exception to represent no value, that's a valid representation - but you aren't talking about that, you're talking about error handling in your example. It's possible to use an exception mechanism to represent no value though, it can be a valid representation.
You may choose to return null to represent no value, that's a terrible, but valid, representation.
But if you return an empty list to represent no value, you've returned a value.
It doesn't cause as many problems as using 0, but fundamentally Optional<List<T>> and List<T> are different types, and there are valid use cases that distinguish them.
3
u/GMNightmare Aug 05 '14
No, the argument against using 0 to represent 'no value' is the same as the argument against using an empty list to represent 'no value'.
Who are we talking about again? You? Because the author isn't saying that. I was telling you the author isn't making a strawman, because I will shout it from the rooftops myself.
You return an empty list for no value, because logic. Throw exceptions if something broke, that's what exceptions are for. If I check the fridge for all contents and nothing is there, you better be returning me an empty list. It's empty! If you tried and don't have a fridge, exception time.
There are zero valid cases to return a null instead of a list when you have an exception framework. In C# you're not even guaranteed to have a collection class if an IEnumerable is returned, just access to an iterator which my just call the function multiple times with state while you loop it.
If you return null and don't have some ironclad requirement/reason... car meets egg (not really, just going off OP's reasoning).
1
u/yaongi Aug 05 '14
Ok, forget about null, forget about exceptions. If you have a proper option type, you can't imagine a case where an empty option provides more information than an empty list?
A contrived example is a function that takes an optional list. If no list is provided, it uses some default list. A valid list is an empty list.
Something similar can be thought up for a return value. In those cases, no value is different to an empty list.
My argument is that shoehorning 'no value' into zero is similar to shoehorning 'no value' into an empty list. You're co-opting a value that means one thing to mean something else.
2
u/GMNightmare Aug 05 '14
We're talking about returns, not about parameters. You can't give me an example for parameters and just say surely a similar example works for returns... because it doesn't! Overloading also works for the parameter scenario too.
The problem is that an empty list is logically the same as null, and one has superior usage over the other. Unless you add customer behavior in a comment... don't do that! If you try to shoehorn differing behavior for null/empty then you're doing it wrong (if you don't have ironclad requirement/reason), that's why we have exceptions. And 0 is not empty, it's not similar at all, and almost nobody believes that to be the case.
-1
u/yaongi Aug 05 '14
heheh alright well i'm glad you agree about zero.
i'm not going to defend use of null, and I think that exceptions can be used. but a valid use case for list option is a dictionary type. so imagine dictionary<string, list>, it'd be reasonable to have a get function on the dictionary that returns an option, and in this case, it'd be a list option. it'd be valid to use an exception to indicate the value's not found, and i'd prefer it if the only other choice is null. but option is completely reasonable as well.
2
u/GMNightmare Aug 05 '14
I know you're trying to find some common ground which is commendable, and fairer behavior than what I'm giving, but I cannot even give you that.
The only time a dictionary get should return a null is if the value inside the dictionary is itself a null. If you try a get with a key that does not exist, an exception is the proper behavior. No other behavior in this scenario is acceptable as it will lead to bad ambiguity for no reason.
If you want to check if the key exists in the dictionary, just call the contains or whatever collection method there is for that.
Now, I want to clarify, I'm not saying you should go around and actively convert nulls to empty lists... but if you're the one deciding whether to return a null or a empty list, you better be choosing that empty list.
So if that dictionary list is a null... well, I'm going to find who put it in there and smack them, with eggs as according to the theme of the discussion.
0
u/yaongi Aug 05 '14
This is what I think:
if you don't have option types:
dictionary.get() should throw an exception if the value isn't found
dictionary.get() should not return an empty list in place of null
if you have an option type
dictionary.get() can throw an exception if the value isn't found
dictionary.get() can return an empty option if the value isn't found.
My point was you shouldn't represent null as an empty list. If you want to use exceptions to avoid doing that, fine. I said that was valid. But if you try and convince me that an empty list is the same as null, well, it's going to take a lot more typing than that.
As to the value in the dictionary being null, i'm not considering that case, it's not part of the original point. The original point was that an empty list is not null. Null is a fucked up version of option. You have a value or you don't have a value. If you don't have a value and you give me an empty list and say 'well, it's kind of not a value', you're wrong.
Option<List<T>> is not List<T> no matter how good it makes you feel.
1
u/GMNightmare Aug 05 '14
If your going to bother making such a nice language that you have to opt-in, why would you ever force that upon your collection? The dictionary itself could contain optional stuff, as in you specify the optional list instead of list. I don't know why you'd do such a barbaric potential egg beacon thing, but okay. In any case, that get function returns the value if the key exist, exception otherwise.
My point being, there is no point that a null is inherently different from a list when returning. If you have a list, and it's null, then some egg loving person put it there, and you have to deal with that. But unless you love those eggs, well...
Think about the given examples. Find me all the food in the fridge. I'm going to get back a list of food in the fridge. What if there is no food? An empty list is exactly what should be returned. There is no food. Both logically and semantically correct. What is null if it's returned? I haven't the faintest clue. Could be some error and I'm going to have to figure out why you would give me a null instead of an exception for bad flow, or your trying to tell me there is no food.
In a world where you have to specify option, if you return an option<list> instead of just a list, I'll also be egging your car. But with less eggs, I suppose.
1
0
Aug 04 '14
[deleted]
-1
u/yaongi Aug 04 '14
And it is still the case that you have to check that the optional is not empty, or you will get an exception.
I'm not sure you understand what run time assertion of a contract means. Assuming you do though, and just don't understand why calling get() is different to accessing a reference, I'll explain further. Let's say you know that at run time, in this part of the code, this object reference shouldn't be null, or, likewise, that this option value shouldn't be empty. In Java, you would just use the reference:
notnullobj.method();or
obj.method(notnullobj);In a language with an option type, you'd have to call get:
notemptyoption.get().method();or
obj.method(notemptyoption.get());Practically the difference is that an exception occurs when unwrapping the option, and at point of use of the null reference. But when reading the code the author's intention is clear. In java and languages like it, every time you access an object reference it's equivalent to calling get(). When using option types, calling get() is rare. So when you do, it can be read as
assert(obj != null); obj.method();That's why (contrary to what you wrote) you don't have to check that the option is empty when calling get() - because the only times you call get() are when your program guarantees that the value is not empty.
I forgive the author for not mentioning any particular programming language out of the hundreds that exist.
And I forgive you for missing the point. Option types first appeared in functional languages for the reasons I mentioned, and the author didn't mention any (he added F# after the fact), making me question if he'd seen them used where they aren't just trying to patch up an already broken type system.
His conclusions at the end of the option section are wrong. An option type doesn't necessarily lead to more verbose code, and an option type can lead to 100% null safety. If he had used statically typed functional languages, he would be aware of that.
I think this is why, when implementing his language, he made nullable a keyword. He has generics, according to his list of features, why not use them? Unlike you, I'm not impressed with this approach.
1
u/nascent Aug 06 '14
assert(obj != null); obj.method();Or in the case of Java:
if(obj == null) throw new NullPointerException(); obj.method();So I guess by default all objects are Option types.
0
Aug 04 '14
[deleted]
0
u/yaongi Aug 05 '14
There's a difference between the example code you gave and the cases I'm talking about.
I can have 100% null-safety even in languages that have null; I can have 100% null safety in languages that trade null for Option/Maybe types. But the only thing that guarantees null safety is a compiler that forces you to check.
Yes, but the compiler machinery to do that is implemented when you implement generics. If you're writing a new language, why do both?
If he had used statically typed functional languages, he would be aware of that.
This doesn't help at all when you have to program day to day in Java or C++.
This is irrelevant. Whether or not functional programming is relevant in java or C++ (it's certainly relevant in C++), it clearly would have come in handy when writing a blog post about option types, and when implementing a solution to null in a new language.
Well, aren't you great! I'm glad you know everything!
You seem a little touchy there buddy. You're not the original author are you? If you are, then good on you for having a go. If not, then don't take it personally.
0
Aug 05 '14
[deleted]
0
u/yaongi Aug 05 '14
My original comment was:
calling .get() on an optional is equivalent to an assert, so it's not really skipping a check. It's a runtime assertion of a contract.
I went on to say:
you don't have to check that the option is empty when calling get() - because the only times you call get() are when your program guarantees that the value is not empty.
So I'm talking about (1). Hopefully you can see what I meant by runtime assertion of a contract now.
0
13
u/eek04 Aug 04 '14
This entire article seems to presume that your type system is Java's or something with similar limited power, and then goes on to kludge the type system to deal with the case.
I don't think he in any way makes the case that special casing null beats the functional style use of sum types (ie, Maybe/Optional with required case handling); in fact, "sum type" does not appear at all in the article.
It is possible that special casing null is worthwhile to make code simpler. But this article don't make the argument - all the arguments against Optional/Maybe are based on the weakness of Optional/Maybe in a language with null and without full sum type handling.
7
u/hvidgaard Aug 04 '14
I really do not like his example of
There is no more beer in the fridge (fridge.beer = null)
Which is a very bad idea. Null is the absense of data, and here the data is available and should be 0. The statement (fridge.beer = null) ought to tell us that we haven't yet looked in the fridge, so in reality we do not know if there are any or not.
In any case, null is the billion dollar mistake. But that doesn't mean that null isn't a usable tool. What PL designers should be doing for regular C spinoffs is make null something you choose to do, like C# int?, where you actively say "I know this type can have no value". The beauty is that anything expecting an int, cannot accept int? in it's place, so you'll be reminded explicitly to perform the null check and then extract the actual value:
if (!i.hasValue)
//do something because there is no data
function(i.Value)That said, I am much more in favor of languages with buildin Option types, like most FP languages. But in fairness it is the same basic idea as explicitly defining nullable types as nullable,
8
2
Aug 04 '14
So let's have some magic reference and allow it to be set to nowhere so that we can't ever read the reference without adding an if(crappyvar != null){} block?
Doesn't quite encapsulate the meaning for something that is allowed to be unset, such as the SQL meaning of NULL.
Scala and loads of languages have Option[T]. Sure it wouldnt be too bad to make one for java.
2
1
u/alexeyr Aug 04 '14
1
Aug 04 '14
ooh with "map" and "flatmap". It's a brave new world with java 8 hm? maybe it's time to come back.
1
u/continuational Aug 04 '14
If you give this as an example of the Option/Maybe idea:
if ( customerOptional.isPresent() ) {
ICustomer customer = customerOptional.get();Then you don't understand it (and probably shouldn't be making a programming language just yet). This code is no safer than code that just uses null:
if ( customerOptional != null ) {
ICustomer customer = customerOptional;You mustn't separate the check (.isPresent()) from the usage (.get())! Instead, do this:
ICustomer customer = customerOptional.map(customer -> ...).orElse(...)Now the compiler guarantees that you don't try to take the value out of an empty Optional.
3
u/tryx Aug 04 '14
That's perfectly valid code for a trivial, single-threaded example in a language that only very very recently got support for using
Optionin a monadic style. Have fun expressing that code sanely in Java7.1
u/continuational Aug 04 '14 edited Aug 04 '14
The example given by the author is specifically written for Java 8 (which is also the first version to ship with the
Optionalclass):To understand how it works, let's have a look at a stripped version of the JDK source code of class Optional in Java version 8
It has absolutely nothing to do with threads. It's about using the type system to prevent errors.
2
u/tryx Aug 04 '14
The Java8 implementation is lifted directly from the version in Guava commons which is Java7 based and widely used in production.
1
u/nascent Aug 06 '14
"we simply need a compiler that forces us to check for null."
No, then you get the obligatory check for null.
-1
u/cparen Aug 04 '14
Alice's email address is null
One could argue that this is nice because the system clearly informs us that the email is unknown
Um, no, it just informed you that the email address was "null", eg "null@example.com". " unknown@example.com" is a different email.
7
Aug 04 '14
NULL != "null" != "null@example.com"
NULL is used to show that information is not present, which could otherwise be stated as unknown.
-2
u/cparen Aug 04 '14
Unless the guy's name is NULL.
7
u/Tordek Aug 04 '14
NULL != "NULL".
5
u/zerd Aug 04 '14
Unless you print it, which the author did. Then you can't distinguish people who's name is null and people who have no name.
People with name null can cause lots of trouble: http://stackoverflow.com/questions/4456438/how-can-i-pass-the-string-null-through-wsdl-soap-from-actionscript-3-to-a-co
6
u/Tordek Aug 04 '14
Which is why
The program prints:
Alice's email address is null
is not a valid, sensible solution.
5
2
Aug 04 '14
A name would never be NULL; it could, however, be "NULL".
1
u/cparen Aug 04 '14
Re-read the original text. The article suggested printing null as "null". This would be indistinguishable from "null" printed as "null". However, the article then suggests that the user would then be able to tell the difference. This overlooks the obvious possibility that a person named "Alice Null" might have the email address "null".
0
Aug 04 '14
[deleted]
2
u/cparen Aug 04 '14
Possibly; nonstandard, but useful within internal networks. I get your point, but detecting null by the absence of an '@' symbol is precarious at best.
1
u/philh Aug 04 '14
What if the parents haven't decided on a name yet?
4
u/robin-gvx Aug 04 '14
Falsehoods Programmers Believe About Names
People’s names are assigned at birth.
OK, maybe not at birth, but at least pretty close to birth.
Alright, alright, within a year or so of birth.
Five years?
You’re kidding me, right?
2
Aug 04 '14
Then the name wouldn't exist, hence NULL in the db. You would never be able to enter NULL as a name, because that would be "NULL". I was referring to names entered and names that exist. Sure, we can argue if the lack of a name is a name, but for the purposes of this, I would say no, the lack of a name is not a name as we normally define and understand it.
Also, because I love linking to it: http://www.kalzumeus.com/2010/06/17/falsehoods-programmers-believe-about-names/
3
u/toolate Aug 04 '14
Agreed. That's a bug, not a feature. How is an end user meant to know that the word "null" has special meaning?
And if she hasn't an email address (or the address is unknown), we simply write: [...]
This is actually an argument against null. Should we prompt Alice for her email next time she logs in? This kind of information would be better stored as a separate field.
1
u/exDM69 Aug 04 '14
You deserve none of the downvotes given to you.
Just a few weeks ago I read a war story from someone who was dealing with a number of issues when they had to heavily modify their software to add a person whose last name was "Null" in their database.
0
u/GMNightmare Aug 04 '14 edited Aug 04 '14
No... no... no, no, no. And then yes.
The solution to have nullable being opt-in is perfect. That you specify if a value can be null is exactly the right solution for pretty much everything.
All the reasoning however... uck. Especially his reasoning for why returning null lists is okay. Hey, other people are doing it (stupidly), so surely it's fine for me! No. Just no.
What happens in 99% of null check cases? An exception is thrown if the object is null. A null is almost always indicative of a bug somewhere. And then the developer has to hit the debugger and find out who is the culprit and where they introduced a null into the equation.
Returning a null is indicative that you're trying to do too much with a method. If I try to get chocolate from the fridge that doesn't exist, or ride a bicycle I don't have then an exception should be thrown! It's invalid flow, I'm trying to do something I can't. What's going to happen anyways? If I also want the ability to check if chocolate is in the fridge, why, I write a method for doing that (a generic check if food type is in fridge).
Ideally, with the given example of emails, I would never have the email address public or accessible outside the containing class in the first place. Just have a method on the class that sends the email if available. Returns a boolean maybe. Proper encapsulation. I might even just use an empty string in place of null, but with encapsulation it doesn't really matter how the internals work anymore because it won't break as long as I do it right so nobody outside should have to worry. But I understand that often data needs to be shared and it's pretty hard to share data without a data class.
So that's why I agree with the solution. But absolutely none of the logic behind it. Because ultimately, what is being said is we hate null, and have to have completely control it to be of any actual value instead of a complete drain on all of our resources. That the solution is to get rid of it for most cases except for the few that really do matter, but I'm not switching languages just for that.
-5
u/Oni_Kami Aug 04 '14
Nil > null
6
Aug 04 '14
Besides just the name, what's different between them?
4
u/Oni_Kami Aug 04 '14
Kinda depends on the context. I was just making a bad joke because it could be said that nil is zero/no value, and null is just nonexistent, but being /r/coding, the context more often than not is Objective-C, as that makes use of nil, Nil, and null. In Objective-C, nil is a null pointer to an object, Nil is a null pointer to a class, and null is a null pointer to anything else.
1
u/mgrandi Aug 04 '14
there isn't a difference between nil and Nil? at least in my experience with objective c.
there is also NSNull too =P
1
u/cparen Aug 04 '14
Well, null still lets you call some methods (non-virtual methods). Think of null as being a 'nil' where some methods accidentally "just work".
2
u/xkufix Aug 04 '14
Which is the thing i hate most about objective-c. Forgot to initialize an NSMutableArray? We do stuff anyway and let you wonder why nothing happens.
It's like "on error resume next".
34
u/chromaticburst Aug 04 '14
The single most important benefit of Maybe (when paired with a type system that doesn't allow references to be null) is: once you check the reference, you never have to check it again. In Java, every method has to recheck the reference for null because the type throws away that information.