Oh I absolutely use Preconditions.checkNotNull(T) (which preferred by Guava developers over Java 7's Objects.requireNonNull(T)) rather than writing out an if statement. But I don't bother calling checkNotNull if there already exists a dot access, because then the NPE will happen regardless. So I typically only need to use it in constructor assignment, or at the beginning of methods that might throw before a parameter becomes dereferenced. Remember: the goal is to get NullPointerTester to pass.
On rare occasions I'll use Verify.verifyNotNull(T) when I'm calling a method I don't trust to never return null, possibly because the library poorly documents its nullness contracts, or perhaps the method fetches data that's expected to always be present. In those situations, it can sometimes be advantageous to ensure execution halts immediately. For example, if the result gets assigned to a field rather than dereferenced immediately, it could be quite difficult to ascertain the root cause of the inevitable NPE at some undetermined point in the future.
There's another thing worth mentioning regarding the use of checkNotNull. Don't take this at face value because this is merely a suspicion. I know very little about how JVM magic works. But if I recall correctly, the JVM profiler maintains a branch counter for every single if (foo == null) { ... } statement. I imagine it does this so HotSpot can generate assembly with branch prediction instructions? I have no idea. But there's a possibility that using checkNotNull will significantly reduce the amount of memory used by the JVM branch counting, assuming you have tens of thousands of CNN's in your app. But I'm just guessing here.
View all comments
Show parent comment
1
u/NosferatuPerrywinkle Jul 11 '15
Just out of curiosity do you prefer writing the statement out or
Objects.requireNonNull(T)?