5

Good morning stackoverflow,

I'm currently implemeting a visitor pattern on something like an AST. Now my question is, how do I iterate through the elements ?

I think its somewhat more logical to just return the object to the visitor and let the visitor traverse from there on. Because you're keeping up flexibility , when you would like to traverse the object in different ways.

On the other side one could say, the visitor shouldn't concern about the structure of the object. So in case the object changes, you don't have to change the visitor too.

Are there any general recommadations how to solve this? I've got two books about Visitor Patterns but both are not dealing with the question how to deal with more complex nodes.

Regads toebs

toebs
  • 389
  • 1
  • 2
  • 13

1 Answers1

2

It seems pretty straightforward for a tree structure. The accept method in a node could look like this:

void accept(Visitor visitor) {
    visitor.visitMyTypeOfNode(this);
    for each child {
        child.accept(visitor);
    }
}

Obviously you need to consider if this makes sense in the overall architecture of your application.

pablochan
  • 5,625
  • 27
  • 42
  • Well yes, this is one way. You could also just return the object and iterate in the visitor right? Is there any trade off I cant think of or would it be the right way to implement two different accept methods?(in case you would like to traverse your object in different ways) – toebs Nov 18 '13 at 12:36
  • 1
    Iterating in the visitor never makes sense since it reintroduces the problem the visitor solves in the first place (checking the type of object to perform an operation on). An alternative to my answer could be using an external iterator mechanism. – pablochan Nov 18 '13 at 12:43
  • 1
    Regarding my previous comment: It might make sense to iterate in the visitor if it makes sense in the context of the performed operation. – pablochan Nov 18 '13 at 12:50