Avoid Class Comparisons
If
you’ve worked with DOM, you know that one of the
most common operations is tree walking. In fact,
the last best practice showed a helper method to aid in this by
walking a node’s children to get its textual
content. This tree walking is generally accomplished through the
org.w3c.dom.Node
interface, as all DOM structures implement (actually, they extend,
and your parser provides implementations of those interfaces) this
base interface.
The problem is that there are several methods for determining a
node’s type, and then reacting to that type. Most
Java developers familiar with polymorphism and inheritance would
immediately use the methods provided around the
Java
Class
class. Using that approach, you might end up
with code such as that in Example 5-13.
NodeList children = rootNode.getChildNodes( ); // Figure out which node type you have and work with it. for (int i=0; i<children.getLength( ); i++) { Node child = children.item(i); if (child.getClass( ).equals(org.w3c.dom.Element.class)) { Element element = (Element)child; // Do something with the element. } else if (child.getClass( ).equals(org.w3c.dom.Text.class)) { Text text = (Text)child; // Do something with the text node. } else if (child.getClass( ).equals(org.w3c.dom.Comment.class)) { Comment comment = (Comment)child; // Do something with the comment. } // etc . . . }
In a similar vein, I’ve also seen code that looks similar to Example 5-14.
Get Java Enterprise Best Practices now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.