Visitor Pattern: Traversing tree elements in client or visitor
Asked Answered
B

1

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

Broadbent answered 18/11, 2013 at 9:41 Comment(1)
Related question: #24566281Nightgown
S
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.

Sabelle answered 18/11, 2013 at 11:36 Comment(3)
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)Broadbent
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.Sabelle
Regarding my previous comment: It might make sense to iterate in the visitor if it makes sense in the context of the performed operation.Sabelle

© 2022 - 2024 — McMap. All rights reserved.