wood burning stoves*
The moose likes Beginning Java and the fly likes Check Parameters for Validity Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Check Parameters for Validity" Watch "Check Parameters for Validity" New topic
Author

Check Parameters for Validity

Freddy Wong
Ranch Hand

Joined: Sep 11, 2006
Posts: 959

I've been reading Effective Java book. It's a very good book, indeed. Is it actually necessary to check every parameter for a null and then throw a NullPointerException if the parameter is null? It seems that a method will be cluttered with a lot of if conditions if we need to do so.

Please share your opinion. Thanks


SCJP 5.0, SCWCD 1.4, SCBCD 1.3, SCDJWS 1.4
My Blog
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19656
    
  18

It depends.

First of all, does it matter if the parameter is null? For instance, in java.io.File#listFiles(FileFilter), it uses the following to see if a file is accepted:

If you can do this, just let the parameter be null.

But let's assume it can't be null. If the method / constructor itself always calls a method on that parameter, I just let it throw the NPE for me. In all other cases I put in the check.

However, being the lazy guy that I am, I've created a utility method for that:

Called:

I have even a similar method for collections to check if any element is null as well.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Freddy Wong
Ranch Hand

Joined: Sep 11, 2006
Posts: 959


Yup, I agree with that, and that's what I normally do. But according to the book, it's actually a good practice to check for a null instead of letting the parameter throws a NullPointerException as a result of referencing a null. That way, the debugging will be easier.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38075
    
  22
I think what Bloch means is that you need to avoid the case where you don't throw an NPE; if your method passes the null to something else which passes the null to something else which passes the null to something else which puts it in some record whence it is retrieved and throws an Exception . . .

You will have no end of difficulty working out what happened.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Check Parameters for Validity
 
Similar Threads
request.getParameter() from same page as HTML FORM
checkboxes
JSP Request Object
Problems with form validation
Implementation for item 3.3