Every method accepts a set of parameter values. Should we always validate the non-nullness of input parameters or allow the code to fail with classic RunTimeException
?
I have seen a lot of code where people don't really check the nullness of input parameters and just write the business logic using the parameters. What is the best way?
void public( String a, Integer b, Object c) { if( a == null || b == null || c == null) { throw new RunTimeException("Message..."); } .....business logic..... }
It is a good idea to check for null explicitly because: You can catch the error earlier. You can provide a more descriptive error message.
In Java you can't define more than 255 pararmeters for a method. This is the restriction.
The best way is to only check when necessary.
If your method is private
, for example, so you know nobody else is using it, and you know you aren't passing in any nulls, then no point to check again.
If your method is public
though, who knows what users of your API will try and do, so better check.
If in doubt, check.
If the best you can do, however, is throw a NullPointerException
, then may not want to check. For example:
int getStringLength(String str) { return str.length(); }
Even if you checked for null
, a reasonable option would be throwing a NullPointerException
, which str.length()
will do for you anyways.
No. It's standard to assume that parameters will not be null and that a NullPointerException will be thrown otherwise. If your method allows a parameter to be null, you should state that in your api.
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