Saturday, March 12, 2011

Avoid null if possible

Some argue that allowing null into the API of a class, in the form of possibly-null parameters or return values, should be avoided if possible :

  • null references can only be used in a boolean test - any other use will throw a NullPointerException
  • null references always represent special cases, and if these special cases can be removed, the code will be easier to understand
  • null return values are error prone, since there is no way to ensure that the caller always does a check-for-null.
  • methods which accept an explicit null reference as a valid argument are less intelligible at the point of call. The reader will usually need to consult documentation to determine what exactly the null argument means.

If null is allowed for a method, then this should be clearly stated in its javadoc. Some follow the convention that all items are assumed to be non-null unless otherwise specified. Such a convention could be explicitly stated once in the javadocoverview.html.

See also use zero sized arrays rather than null

No comments:

Post a Comment

Chitika