Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should we always check each parameter of method in java for null in the first line?

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..... } 
like image 734
Sanjeev Kumar Dangi Avatar asked Mar 02 '11 20:03

Sanjeev Kumar Dangi


People also ask

Why is checking for null a good practice?

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.

How many parameters should a method have Java?

In Java you can't define more than 255 pararmeters for a method. This is the restriction.


2 Answers

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.

like image 54
iluxa Avatar answered Sep 23 '22 23:09

iluxa


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.

like image 38
Robby Pond Avatar answered Sep 22 '22 23:09

Robby Pond