tl;dr - it is GOOD to check for unexpected nulls but BAD for an application to try to make them good.
Details
Clearly, there are situations where null is a valid input or output to a method, and others where it is not.
Rule #1:
The javadoc for a method that allows a null parameter or returns a null value must clearly document this, and explain what the null means.
Rule #2:
An API method should not be specified as accepting or returning null unless there is a good reason to do so.
Given a clear specification of a method's "contract" vis-a-vis nulls, it is a programming error to pass or return a null where you shouldn't.
Rule #3:
An application should not attempt to "make good" programming errors.
If a method detects a null that shouldn't be there, it should not attempt to fix the problem by turning it into something else. That just hides the problem from the programmer. Instead, it should allow the NPE to happen, and cause a failure so that the programmer can figure out what the root cause is and fix it. Hopefully the failure will be noticed during testing. If not, that says something about your testing methodology.
Rule #4:
Where feasible, write your code to detect programming errors early.
If you've got bugs in your code that result in lots of NPEs, the hardest thing can be figuring out where the null values came from. One way to make diagnosis easier is to write your code so that the null is detected as soon as possible. Often you can do this in conjunction with other checks; e.g.
public setName(String name) {
// This also detects `null` as an (intended) side-effect
if (name.length() == 0) {
throw new IllegalArgumentException("empty name");
}
}
(There are obviously cases where rules 3 and 4 should be tempered with reality. For instance (rule 3), some kinds of applications must attempt to continue after detecting probably programming errors. And (rule 4) too much checking for bad parameters can have a performance impact.)
@throws NullPointerException If paramx is nullto the method Javadoc comment. – biziclop Feb 23 '11 at 20:16