Commandments of Java Programming #4

h2. The law of null

# _Every non-private method shall never return null._
# _Every non-private method shall check every parameter for null._

While one school of thought proposes ever new languages to
take care of this issue (a recent example is nice).
I think that these simple rules help us to fend off NPEe trouble .

h2. Implications

# This is especially true for lookup functions which shall never return null
if the lookup fails. An Exception is more appropriate, perhaps even
a checked one – but have a nice error message like “could not look
up database server”. A prominent example that fails here is HashMap and friends.
The Performance argument is invalid if a check mehtod is
provided, such as contains(). A timing critical client can then
avoid the exception, by checking first (It’s also overhead, but hey it’s 2005).
# This does not mean that a null passed into a parameter breaches
the contract of the method. Null can be used to circumvent the
lack of optional arguments in java.

h2. Apart from that

In private methods, fields, and local variables null can be a good
way to indicate uninitialized fields and save additional flags (thereby eliminating redundance).


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.