Please ref to the demo code:
git clone https://github.com/AlphaWang/guava-demo.git
Many of Guava’s utilities are designed to fail fast in the presence of null rather than allow nulls to be used.
1 2 3 4 5 6 7 8
Additionally, Guava provides a number of facilities both to make using
null easier, when you must, and to help you avoid using
Null object pattern
- Consider if there is a natural “null object” that can be used.
If it’s an enum, add a constant to mean whatever you’re expecting null to mean here.
java.math.RoundingMode has an
UNNECESSARY value to indicate “do no rounding, and throw an exception if rounding would be necessary.”
example 2: use Unit.NONE instead of
1 2 3 4 5 6 7 8 9
- Never return null.
For example, return a empty list instead of null.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Optional<T> is a way of replacing a nullable T reference with a non-null value.
Besides the increase in readability that comes from giving
null a name, the biggest advantage of Optional is its idiot-proof-ness. It forces you to actively think about the absent case if you want your program to compile at all, since you have to actively unwrap the Optional and address that case.
there are two main use cases of
- remind your client that the returned value can be null, can force he to check null case: api:
1 2 3 4
1 2 3
- return a default value if the object is null:
Enums#getIfPresent can help to get an Optional
1 2 3 4 5 6 7 8 9 10 11
MoreObjects.firstNonNull is an alternative of
Optional.or, both can return a default value if the object is null.
Of course we can fail fast in the presence of null, just like guava code. Guava provides
Preconditions.checkNotNull to do this.
1 2 3 4 5 6 7
- Guava User Guide : https://code.google.com/p/guava-libraries/wiki/GuavaExplained
- Getting Started with Google Guava : http://pan.baidu.com/s/1o6LZJf0