Shared publicly  - 
 
Guava users: do you use @Nullable in your projects? I'd very much like to configure my static analysis tool (findbugs? I think that's the nicest one around?) to assume parameters are non-null unless marked up with @Nullable.

Is it actually worth it to spend the effort doing this, though? Same goes with the Optional<> type. When used correctly, Optional gives you pretty much the same thing as a regular nullable parameter does: the ability to check of the value is present, and an exception if the value is "dereferenced" when it isn't present. What you gain is some readability - it's clear to readers that an Optional<String> can be present or not. You also lose some readability - consumers of your interface must wrap all inputs in Optional.of() or Optional.<String>absent() (yuck).

Additionally, the Optional reference can ITSELF be null...

It seems to me that the best thing to do is add the @ParametersAreNonnullByDefault package annotation to all your packages, explicitly use the @Nullable annotation on optional parameters, and forget the Optional type.

Thoughts?

Looking at you, +Louis Wasserman... :)
2
1
Jordan Lewis's profile photoKevin Bourrillion's profile photoKurt Alfred Kluever's profile photoLouis Wasserman's profile photo
4 comments
 
Opinions vary. I do use @Nullable and @ParametersAreNonnullByDefault, but sometimes I use Optional.

Probably the single biggest disadvantage of null is that it's not obvious what it should mean in any given context: it doesn't have an illustrative name. It's not always obvious that null means "no value for this parameter" -- heck, as a return value, sometimes it means "error", or even "success" (!!), or simply "the correct answer is <nothing>". Optional is frequently the concept you actually mean when you make a variable nullable, but not always. When it isn't, we recommend that you write your own class, similar to Optional but with a different naming scheme, to make clear what you actually mean.

But I would say the biggest advantage of Optional isn't in readability: the advantage is its idiot-proof-ness. It forces you to actively think about the absent case if you want your program to compile at all. Null makes it disturbingly easy to simply forget things, and though FindBugs helps, I don't think it addresses the issue nearly as well. This is especially relevant when you're returning values that may or may not be "present." You (and others) are far more likely to forget that "other.method(a, b)" could return a null value than you're likely to forget that "a" could be null when you're implementing "other.method." Returning Optional makes it impossible for callers to forget that case.
 
Thanks, Louis. That makes a lot of sense.
 
Also, we don't recommend using Optional for parameter types for exactly the reason you show, and because you can often address its "optionalness" using overloads that do and don't take that value.
Add a comment...