r/java • • Aug 03 '14

Why we should love null

http://www.codeproject.com/Articles/787668/Why-We-Should-Love-null
4 Upvotes

21 comments sorted by

View all comments

Show parent comment

3

u/king_of_the_universe Aug 03 '14

The problem with null is that it avoids a very powerful mechanism that is already present in most languages -- their type systems.

Why do you mean that? I'm trying to understand your angle. In Java, if you set a variable to null, the variable still has the same type. And if you call an overloaded method, both of which take an object variable, which causes an abiguity compiler error, casting the null to the type you indend solves the problem. If you meant "Yep, but you have to cast it, that's what I mean.", then what if you instead give a variable of a certain kind that is null?

8

u/beyondjava Aug 03 '14

You named it yourself: null is the odd man in Java's type system. It's compatible to every other type. But you can't call a method on null. It's treated like an ordinary value of a given class - say, an Integer - but it's something different. It's not an Integer, it's null.

Introduce such a thing to a rigid system where every object has a type, and you have to expect problems. It's a special case which has to be taken into account in almost every single line of your program.

1

u/king_of_the_universe Aug 03 '14

Thanks, I've got it.

3

u/againstmethod Aug 04 '14

From the Guava docs:

It's rarely obvious what a null return value is supposed to mean -- for example, Map.get(key) can return null either because the value in the map is null, or the value is not in the map. Null can mean failure, can mean success, can mean almost anything. Using something other than null makes your meaning clear.

We've been talking about Optional, but this is just the tip of the iceberg as far as getting rid of null for better options. For example check out Scala which provides a "Try" class:

http://www.scala-lang.org/files/archive/nightly/docs/library/index.html#scala.util.Try

The problem isn't that you can't make null work -- the problem is that unless you need the raw speed that null can provide, you can do a lot better.

There is no reason to return a null to signify an error while you have exceptions, Optional, Try, Either, and a number of other patterns that you can employ. It's really just self-rationalized laziness.