[jdom-interest] The JDOM Model, Chapter 15 of Processing XML with Java

Laurent Bihanic laurent.bihanic at atosorigin.com
Tue May 7 07:45:35 PDT 2002


Elliotte Rusty Harold wrote:
> Sounds complex to me. I prefer a single, more powerful Node interface. 
> Part of the goal is to remove a lot of the casting and testing that's 
> necessary now. This just seems to move it to a different level. Still I 
> suppose it could solve the other half of the problem, which is the 
> collections API returning Object.
> 
In all the discussion I had with Jason on that subject, one of Jason's main 
concerns was not to add "useless" methods to any class. With this in mind, 
it's impossible to add methods dealing with parent or siblings (because 
Document does not have any of those), name (because only Element et Attribute 
have one) or children (because only Document and Element have those).

After a while I kind of like Jason's vision because it steers JDOM away from 
having classes displaying a huge number of public methods (such as Swing 
JTable for example). The API is easier to grasp.

And just like him, I think useless methods are a bad idea. For example, how 
would you implement getName() on Comment or getParent() on Document?

Returning null is bad. IMHO, littering the application code with "if (xxx != 
null)" statements is worse than requiring the programmer to test and typecast 
before calling the method. For getParent, how do you distinguish between a 
null parent (e.g. an element detached from any document) and an invalid call 
(e.g. getPrent on Document)?
Throwing a runtime exception is also bad because it's just another way to 
force the programmer to test the node type.

Hence the idea of the three interfaces: The Node one to have a single common 
interface and the other two (leaf and branch) to ease visiting the documents.
Visiting upward always return BranchNodes, visiting downward always return 
LeafNodes (as Element would implement both interfaces).

Finally, using a bitmask allows to flag nodes as implementing commplementary 
interfaces such as TextContentNode (CDATA, Comment, etc.) or NamedNode 
(Element and Attribute) for example.
Personnally, I thing the following code is OK:
    if ((node.getNodeType() & NamedNode.NAMED_NODE) != 0) {
       return ((NamedNode)node).getXxx();
    }
With Node implementing a hasFeature method, it can even become:
    if (node.hasFeature(NamedNode.NAMED_NODE_FEATURE)) {
       return ((NamedNode)node).getXxx();
    }
Not worse than any "!= null" test.


> I've suggested simply adopting the XPath rules here. The biggest problem 
> with not having this method is that it's really not possible to easily 
> get the string content of an element.
> 
Yes but is the string content of a document meaningful?

Laurent





More information about the jdom-interest mailing list