File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Check Parameters for Validity" Watch "Check Parameters for Validity" New topic

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

Joined: Oct 27, 2005
Posts: 20271

It depends.

First of all, does it matter if the parameter is null? For instance, in, 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:


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

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

Joined: Oct 13, 2005
Posts: 46345
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.
I agree. Here's the link:
subject: Check Parameters for Validity
It's not a secret anymore!