Are there any patterns which are similar to Groovy’s safe navigation operator? This is where a null value does make sense and allowing a NullPointerException to be thrown would be wrong.
Other than checking for null, what are some other options? The String class provides a static method to dereference possibly null values but there doesn’t seem to be much use of this pattern apart from the Objects class. Google’s Guava project does have an Optional class but that requires the caller supplying a default which seems too much compared to the safe navigation operator and when you would just want it to be null most of the time. Something that looks like this:
com.google.common.base.Optional.of(fooBar).
or(org.mockito.Mockito.mock(FooBar.class));
The null object pattern or the option monad in Scala are not what I’m looking for or proposals of adding such operators into future versions of Java, I’m looking for patterns that can be applied in Java now.
The “safe” navigation operator is in my opinion a really bad idea since it supresses exceptions and allows developers to get away with error-ridden code.
There are basically just three cases to consider: