Re: An observation about "live" NodeLists

Of course, I can create similar careless-programmer errors with get-next:
     for(Node n=aDocument.getFirstChild();
          n!=null;
          n=n.getNextSibling())
          aDocument.removeChild(n)
which will never get to the second child, because the remove should leave
n's next-sibling set to null.

If you really wanted to do your delete-all-paragraphs loop using the
canonical NodeList interfaces, here's an alternative to the count-down
loop. In my implementation it wouldn't perform as well as count-down, but
wouldn't take as much memory to process.
   NodeList nl = aDocument.getElementsByTagName("p");
   while(nl.getLength()>0) { // While there are matching elements
     Node n = nl.item(0);     // Remove first available match from the tree
     n.getParentNode().removeChild(n);
   }

A programmer has to understand the algorithm they're writing, and what the
side-effects are (including performance effects). With or without NodeList.

Since the DOM is now a Recommendation, NodeLists aren't likely to be
changed for a while. Maybe in a future release (Level 2 or whatever) we can
get them deprecated in favor of other query mechanisms.

Steve's cited program, for what it's worth, would be a problem in any
editable-vector representation; you can get the same behavior out of Java's
Vector with its size and removeElementAt methods. The only unique oddity
here is that people have to be aware that the NodeList _is_ live, and
editing the tree will edit the nodelist.

I don't think NodeLists achieve their goal of simplifying the API, but
let's be fair -- they're not more error-prone, just differently
error-prone. My objection is that they're hugely expensive but (as far as I
can tell) not _less_ error-prone.
______________________________________
Joe Kesselman  / IBM Research
Unless stated otherwise, all opinions are solely those of the author.

Received on Friday, 16 October 1998 16:11:55 UTC