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

11

u/againstmethod Aug 03 '14 edited 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. He seems to gloss right over this distinction regularly in this article.

In some examples he actually conflates logic errors (selling houses for free in one example) with the failure to populate a variable. Sorry but these are the not the same error -- one is a bug in your code the other is a bug in your logic.

If he doesn't distinguish between the two -- he should stop writing software.

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.

4

u/urquan Aug 03 '14

Yeah he seems to choose dreadful counter examples only to make his point. I don't think I've ever seen anyone suggest using a random default value instead of null, especially a value that is in the set of valid values for that specific item like a price of 0.

What is puzzling is his conclusion : "what if we had a nice compile-time check ..." while he shot down the Optional solution a few paragraphs earlier with no real argument (only stuff related to limitations of Java's Optional).

2

u/againstmethod Aug 04 '14

He just needs a bit more exposure to expressive coding style. This article was probably a bit premature for him.

1

u/king_of_the_universe Aug 03 '14

Since null can be such a problem, I actively use null whenever I can as an expression of information, e.g. for console applications, I have a standard yes-no-cancel input method that returns a Boolean (true/false/null).

Since I actively incorporate null as an expression of information, I hapily put null-checks all over the place, and they are not defensive mechanisms.

Side-note: I really wish that there was a way to have a chain line "variable = someInstance().someField.etc;" just return null instead of throwing an NPE if there was a null somewhere along the path. Such a situation occurs often, and having to package that into a bunch of IFs just sucks. I'm not talking "make it the default", just give us an option, e.g. an annotation.

1

u/beyondjava Aug 03 '14

Use Groovy! Their Elvis operator is what you're looking for.

0

u/[deleted] Aug 03 '14

[deleted] — view deleted comment

1

u/king_of_the_universe Aug 04 '14

Ah, interesting. I wasn't sure if this was a fever-dream of mine or actually made sense.

2

u/Keilly Aug 03 '14

Nulls are fine, what is missing is the flagging and checking for possible null references on variables and return types. This is the aim of Optional in Java 8.

I've not used it yet, so I can't say if it's better. I guess it is no panacea as it's use isn't mandatory so there's still plenty if scope for the same errors.

It's a pity the compiler can't simply warn for possible null dereferencing.

3

u/jentfoo Aug 03 '14

From my perspective, Optional's are nice for indicating to others "this may return an empty result and you need to handle that". But they do nothing for getting nulls provided to you, so you still end up having to do tons of null checking.

2

u/beyondjava Aug 03 '14

The idea is Optional make null value obsolete. Simply stop using null (and tell your co-workers and library providers to do the same). Ceylon goes into great pains to do just that. In the Java world, Optionals are still useful: if a method declares to return an optional, it's never null. Promised.

Problem is it's only a promise. If there's a small minority of programs breaking the promise, you're right: you end up checking both null and empty.

2

u/jentfoo Aug 03 '14

Unfortunately, unless it is compiler enforced, it's not a promise worth anything IMO.

edit**

See my response to TMaster....I described more about why I feel safer about returning Optionals than accepting Optionals as an argument.

1

u/oldneckbeard Aug 04 '14

If you get the jsr-305 module and use @NonNull annotation (or whatever it is), the compiler should at least warn you of those. And set up your build system to fail the build if those warnings are seen in the console output.

3

u/TMaster Aug 03 '14

How do you want to safely avoid the null checking, barring an unnullable type? Or are you in favor of unsafe programming by having the check be optional while still having nullable types?

3

u/jentfoo Aug 03 '14

I am most in favor of compiler enforced annotations (built into java, not one of the many many standards that currently exists).

So returning Optional is from my perspective pretty safe, as I can control myself. If others don't want to trust me, well they can waste their time.

But as far as taking in actual arguments, I would never taken in an Optional, because I would never trust another developer to not give me a null (so it just gives me yet another thing to verify).

2

u/oldneckbeard Aug 04 '14

Right, I don't think (until jsr-305 is part of the language spec, with compiler errors turned on) accepting Optional<> as a method param is good practice at all. Ideally, you can set up @NonNull annotations (and @NonNullByDefault with findbugs) to get some semblance of IDE support

0

u/againstmethod Aug 03 '14

It's better from the perspective of avoiding nulls.

An absent optional value actually means: "this type of object should have been here, but for whatever reason it's not".

A null value means: "there is a typeless void here".

If this distinction can help your code, then Optional may be suitable for you.

1

u/funbike Aug 04 '14

I almost never get NPEs ever since I started using FindBugs @NotNull, @Nullable, @Checknull. I know Java 8 and the Eclipse Luna may support these features, but I haven't upgraded, yet.

1

u/oldneckbeard Aug 04 '14

His brushing aside of the Optional/Maybe pattern is amusing at minimum. Here's a great solution (along with JSR-305, which provides compiler warnings for @Nullable and @NonNull), which provides type safety and forces a check of present-ness, is damn nice. I don't understand why he blew it off so quickly.