Sometimes I see developers using libraries like Guava’s Preconditions to validate the parameters for nulls in the beginning of a method. How is that different than getting NPE during runtime since a runtime exception occurs in either way?
EDIT: If there are good reasons, then shouldn't developers use libraries for null-check on all methods?
Some reasons are:
Ultimately it's a matter of taste IMO. I have seen programs that are inherently null safe and don't require pre-conditions at all.
There are various reasons. One big one, as mentioned in the comments, is to get the checking done up front before any work is done. It's also not uncommon for a method to have a code path in which a specific parameter is never dereferenced, in which case without upfront checking, invalid calls to the method may sometimes not produce an exception. The goal is to ensure they always produce an exception so that the bug is caught immediately. That said, I don't necessarily use checkNotNull
if I'm going to immediately dereference the parameter on the next line or something.
There's also the case of constructors, where you want to checkNotNull
before assigning a parameter to a field, but I don't think that's what you're talking about since you're talking about methods where the parameter will be used anyway.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With