Tech Off Thread

5 posts

Forum Read Only

This forum has been made read only by the site admins. No new threads or comments can be added.

Iterating a Composite

Back to Forum: Tech Off
  • User profile image
    ElucidWeb

    So something I really hate doing is iterating over a composite, especially complex ones.  So I have a program that builds a file system Component using the Composite design pattern.  It doesnt take to long to build the entire thing and I have used the Iterator deisgn pattern to build an Iterator class around it. No problem if not annoying to wrap your head around how some if it branches out.

    My question is what experience have you had doing this and any gotchas along the way?  I re-wrote this based on a recursive design I had before that was blowing the stack every now and then, of course thats not good and thats whay Iterator design is the best.

    Just curious, thanks!

  • User profile image
    littleguru

    Yah. Writing an iterator that goes through a composite is just a little challenge. There are also different ways how to iterate through it: For example in a tree, you could do first the current level, then step down or first step down left and then right and then the current level etc...

    The first approach I would do is also the recursive way. If that doesn't work I would look where to inline the recursive part and replace it with a loop.

    Best is to extract the iterator stuff into an own class.

  • User profile image
    eddwo

    Isn't it much easier now with C# 2.0 Iterators?
    You don't have to keep track of the state manually, just write a loop and yield return one value at a time.

  • User profile image
    littleguru

    eddwo wrote:
    Isn't it much easier now with C# 2.0 Iterators?
    You don't have to keep track of the state manually, just write a loop and yield return one value at a time.


    Should be kind of easy with yield Smiley The problem of stack overflow remains... But that is avoided with inlining methods and recursive calls.

  • User profile image
    ElucidWeb

    Well it would certainly reduce the amount of code, albeit it wont be exactly EASY as you put it.  It will be a rather difficult implementation to get it to loop correctly without getting the compiler generating a billion iteration classes for me which yield apprently does for you to my understanding.

    I will mess with it and see how much less code I can get out of it using yield, will be a good learning experience to write a composite iterator using yield anyways since I dont think anyone has done it quit yet!

Conversation locked

This conversation has been locked by the site admins. No new comments can be made.