[jdom-interest] detach() [eg]

philip.nelson at omniresources.com philip.nelson at omniresources.com
Sun Apr 22 13:40:58 PDT 2001

> > 1. If detach() is called on the root element, then an 
> exception is thrown.
> Current mneumonic:
> addContent(elt.clone());  // copy
> addContent(elt.detach()); // move
> Proposed mneumonic:
> addContent(elt.clone());  // copy
> try {
>   addContent(elt.detach());  // try a move
> } catch (IllegalXXXException e) {
>   elt.getDocument().setRootElement(new Element("filler"));
>   addContent(elt);
> }
> I prefer the former.

We seem to have been spending an awful lot of cycles expertly fixing a
problem that barely exists :-)

In the scenario above what matters is not that the element is detached, it's
when and only when the application tries to do something with the document
that the element came from.  Then and only then, it matters if the the
element was the root element.  Then and only then it matters if the
application doesn't put new content where the root element was.  In terms of
use cases I suspect that they probably are in this order.

1 - the document goes out of scope without ever being referenced again
2 - the application replaces the the root element with setRootElement() and
uses the document
3 - failure case where the use has detached the root element and then
outputs the document.  This could occur in indirectly related parts of the

#3 has got to be in the 1 - 5 % use range, don't you think?  My idea of
throwing an exception if you try to access the root element when it has been
detached just gives us a better way to tell the user that the problem has
occurred and with a better error message than a NullPointerException.  In
this scenario, the placeholder element is never accessible to the user.  We
can't output a non well formed document. It probably could be null, it
doesn't matter much really.  If you can't be sure if your document has a
root element or not, you could wrap getRootElement in a try catch block,
similar to Elliotte's idea.  If the normal case was to detach elements
outside of any context of the document, that idea may have made more sense,
but I really think in most cases, the programmer will be aware of the
document when working with the element.  Since we can't say the programmer
will *always* be aware of this, we provide the exception to help explain
what went wrong.

I have been trying to think of other ways we can break the well formed
contract, and I'm still struggling.  However, in this detach scenario it's
really easy to create invalid documents according to a dtd.  In fact we
can't do much about that.

More information about the jdom-interest mailing list