Re: Strategy or Iterator?



Hendrik Maryns wrote:

In Java, this is a candidate for the Strategy pattern: make a class
which does the stuff, and give it as a parameter to the function that
builds the CP.

Other option: have a separate class that builds the CP and have it
return the values incrementally. This sounds like an Iterator: it keeps
track of information, and gives the next() if it is asked for it.

This is the choice between an internal or external iterator. I.e. the choice
between telling some object (internal iteration):
This is what I want done. Do it for
every element in the sequence.
and (external iteration):
If you haven't run out, then give me
the next element in the sequence.

I don't think there's much to choose between them myself.

External iteration is probably somewhat clearer in Java than internal (just
because of the way that Java works, it wouldn't necessarily be true in other
languages). Also you can implement internal iteration easily and efficiently
on top of external, but the reverse is not true (in a language without
coroutines).

Counter to that, if you use external iteration, then you may have to introduce
a new kind of object to hold the elements of the sequence rather than being
able to pass the compound data explicitly as multiple arguments to the
"operation" object. Another reason why external iteration might not be so good
is if the algorithm for producing the elements of the sequence is naturally
recursive, then it may be a pain to convert that to an iterative form.

-- chris


.