[jdom-interest] a question about node type

Michael Kay mike at saxonica.com
Thu Dec 7 15:28:59 PST 2006

> Plus, instanceof is usually an indication of failure of the 
> object model.

Certainly, "instanceof" makes one suspicious. But if you've got a
heterogeneous sequence, like the children of an element node, then the user
is going to have to examine each item in the sequence to see what type it
is, and I don't think that a getNodeType() method is intrinsically better
design than asking the user to do an instanceof test.

I've hit a few very nasty problems recently with objects that implemented
irrelevant interfaces: for example an Element node in Xerces has a
getChildNodes() method that returns itself, which is possible because the
object implements both Node and NodeList; this makes "instanceof" tests
extremely dangerous. (Another example: In the Oracle DOM, document nodes
implement the Element interface). I'm inclined to the view here that the
fault is not in using "instanceof", but in implementing an interface that
doesn't correctly reflect the taxonomy of the object in question.

Of course when you're implementing untyped interfaces like the JAXP XPath
interface, you don't get much choice but to use instanceof to see what kind
of object you have been passed.

There are one or two cases in Saxon where I decided to implement certain
functionality in one place rather than distributing it over a large number
of classes, by using a method that explicitly switches on the type of a
supplied argument. It's not the orthodox solution but I think that it
sometimes makes the code more maintainable.

Michael Kay

More information about the jdom-interest mailing list