Guava - Using and Avoiding Null
I’m starting a series of posts on Guava (Google’s core libraries). Today I am going to start with null, how to use it, and how to avoid it when necessary.
“I call it my billion-dollar mistake.”
Sir C. A. R. Hoare, on his invention of the null reference
Null in Guava Collections
How many times have you expected null values on your collections? And how many times have you actually check to prevent null values on them?
That’s why most of Guava “New Collections” and utilities will fail fast with a NPE when you try to add null to them. And they provide the Optional utilty for those cases where we need to indicate absence of some kind, without using null.
1 2 |
|
Optional
Optional is a way of representing a reference which may be present or not. The whole point of using Optional instead of null, is that there is no way the client can miss the case where the reference is absent. It forces him to actively unwrap the value or else the program won’t compile.
Here is how you create an optional:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
And here is how you query for the value:
1 2 3 4 5 6 7 8 9 10 11 |
|
The next time you are writing a method that return a values which may or may not be present, remember to use Optional. It will make your API much clearer and force the caller to consider the absent value case.