[jdom-interest] getText() and getAttributeValue()
todd.trimmer at trizetto.com
Thu Feb 14 09:32:34 PST 2002
Let me phrase it like this:
Why would any method of any class in any API that returns String want to
return null instead of empty string?
An empty string is analagous to the concept of the empty set. For all
theoretical purposes, empty string will suffice. null shows that not only
does a certain value not exist, but no memory was allocated for it on the
chance that it did exist. If we use 2's complement to remove the ambiguity
of positive and negative zero, why would we want the clutter of both empty
string and null to represent empty set?
The problem with a method returning a null reference when String was
expected is that the returned value might not be examined right away. It
might be passed around to other systems. This can easily lend to the arisal
of the dangerous Null Flag Bug Pattern.
And that's essentially what getAttributeValue() is doing now -- it's
creating a null flag to report an error.
This is the mindset it was written under: the method will return the value
of the specified attribute. If the attribute does not exist, the programmer
made an error by even making the request, therefore return null to notify
him of this.
My proposal is not to "mask errors" (who started this superstition?) but to
gracefully recoup from errors. That's why the empty string is returned. I
know that even though the programmer asked for the value of something that
does not exist, that programmer can still gracefully proceed with an empty
string in his hand. If one were REALLY concerned with making sure the
programmer was aware of his error, getAttributeValue() would have been
written to throw a java.util.NoSuchElementException or such a long time ago.
I daresay that any method of and kind should only return null if that
represents a legitimate working state of the system the method's class is
encapsulating -- never to represent an error, and never when String is the
More information about the jdom-interest