Skip to Content.
Sympa Menu

xom-interest - Re: [XOM-interest] adding an iterator() method to nodes

xom-interest AT lists.ibiblio.org

Subject: XOM API for Processing XML with Java

List archive

Chronological Thread  
  • From: Randall R Schulz <rschulz AT sonic.net>
  • To: xom-interest AT lists.ibiblio.org
  • Subject: Re: [XOM-interest] adding an iterator() method to nodes
  • Date: Tue, 31 Oct 2006 06:52:35 -0800

Steve,

On Tuesday 31 October 2006 06:40, Steve Loughran wrote:
> On 31/10/06, Randall R Schulz <rschulz AT sonic.net> wrote:
> > Don't forget to add the "implements Iterable" clause to enable the
> > concise iteration syntax.
>
> I'm not so sure about that; I think that's a real design error there.
> Because an object can only have return one iterator, something like
> an element has to decide if it will be iterable over its child nodes,
> elements, attributes or namespaces.

It's probably just a compromise between simplicity and generality in the
design of the Java 5 concise iteration syntax. You're forced by the
current definition to pick a single iteration sequence for iteration
over instances of a class that implements Iterable.

As you show below, you can still iterate over arbitrary iterators when
there are distinct methods to retrieve them.

And if there is no single sequence associated with a given class, then
I'd forgo the "implements Iterable" part and just implement the methods
that return iterators. In that case, I would not name any
method "iterator()." But if there's a method that deserves to be the
exalted "iterator()," then I'd "implement Iterable" as well.


> I make my iterators implement iterable instead:
> public Iterator<Node> iterator() {
> return this;
> }
>
> This lets you
>
> for(Element e:root.elementIterator() ) { ... }
> and
> for(Attribute e:root.attributeIterator() ) { ... }
>
> This will probably be considered an abuse of the interface come the
> next edition of Effective Java, but, well, tough.

I don't see the problem with that. There are surely well-designed
classes out there that can yield more than one sequence for iteration.


> -steve

Randall Schulz




Archive powered by MHonArc 2.6.24.

Top of Page