File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Check Parameters for Validity

 
Freddy Wong
Ranch Hand
Posts: 959
Eclipse IDE Java Linux
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Rob Spoor
Sheriff
Pie
Posts: 20396
47
Chrome Eclipse IDE Java Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Freddy Wong
Ranch Hand
Posts: 959
Eclipse IDE Java Linux
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
Pie
Posts: 47293
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic