Fwd: Re: [jdom-interest] NoSuch*Exceptions in JDOM

Brian brian at qcorps.com
Tue Jun 27 17:26:05 PDT 2000


>> // returning null
>> String value = element.getAttributeValue("foo");
>> if (value!=null) {
>>   // something
>> }
>> else {
>>   // something else
>> }
>
>Since there's no getAttributeValue() this really should be:
>
>Attribute attrib = element.getAttribute("foo");
>if (attrib != null) {
>  handleValue(attrib.getValue());
>}
>else {
>  handleNoValue();
>}
>
>Makes me wonder why we don't have getAttributeValue() though.

Oops, sorry about that. The first JDOM source I grabbed a while back did 
have getAttributeValue(), but it apparently didn't make it into beta 4 so 
I added it back. Seems like it would make sense to include it...

>Meanwhile, the exception code needs changes too.

>try {
>  handleValue(element.getAttribute("foo").getValue());
>}
>catch (NoSuchAttributeException e) {
>  handleNoValue();
>}

That does look better, but I often want to keep the attribute value in a 
local variable.

>With the current set of methods, exceptions actually seem to allow for
>simpler code.  Using exceptions also allows you to read an arbitrary
>number of attributes which are all required or implied by the DTD, with
>only one sanity-checking catch clause.  With a null return we'd all be
>too lazy to do n-many sanity checking null return checks, and in some
>cases that'll result in nasty NPEs.

Right, if the attribute is required then its absence is an error and 
throwing an exception is probably best, but if the attribute is optional 
than it's not. I'd still prefer to err on the side of simplicity and 
return null. It's possible that the absence of a key in a Hashtable 
signifies an error in the program, but I wouldn't want Hashtable's get() 
method to declare an exception based on that possibility.

Brian



More information about the jdom-interest mailing list