Is it generally acceptable to allow a Visitor to modify state of the Receiver, or should that be a Command pattern instead?
4 Answers
The purpose of the visitor pattern is to allow new operations to be added to a class heirarchy without modification to that heirarchy. I've never seen anyone suggesting that only read-only operations are acceptable. The only limitation is that the added operations should only use the public interface of the class heirarchy.

- 151
- 4
I don't think you can make a blanket statement whether it's good or bad to modify state of anything. I would think it's ok to modify the states as long as it does not affect the visiting logic itself. For example, you might write a visitor that visits all files under folder structure and renames the file name to upper case.

- 94,654
- 45
- 215
- 319
-
There are definitely cases where one can make the statement that changing the state is a good or bad thing. The Visitor pattern is expected to be used in such a way as a state change is possible and even likely. Whereas with the observer pattern, the observer should not be changing the state. – Pat O Nov 18 '10 at 23:54
-
what about an user, event for commenting, punisher listener which would ban user after saying some violent words? :-) – Kamil Tomšík Feb 06 '11 at 12:33
Microsoft's example of a visitor modifying the receiver is the ExpressionVisitor. The purpose of the ExpressionVisitor class is to modify an Expression tree. So I guess Microsoft at least thinks it's acceptable.

- 9,605
- 6
- 67
- 94
-
1Microsoft isn't always the best guide as to what is right and wrong: http://ayende.com/blog/35841/review-microsoft-n-layer-app-sample-part-xndash-architecture-for-the-space-age – jason Jul 21 '11 at 16:50
-
The standard interpretation when someone says "authority X thinks Y is acceptable" is that you are endorsing Y by appeal to authority X. cf. *argumentum ad verecundiam*. – jason Jul 22 '11 at 03:08
-
3@Jason Sure I'll consider Microsoft an authority. I'm saying here is one instance this authority finding this pattern acceptable. But am I saying they are the "best guide"? No . I leave it up to the asker to decide whether they're right. – T. Webster Jul 22 '11 at 19:09
Each pattern has it's own pros, cons and use cases.
You can use Command
pattern to
Decouple the invoker & receiver of command
Implement callback mechanism
Implement undo and redo functionality
Maintain a history of commands
Use Visitor
pattern in below scenarios:
- Similar operations have to be performed on objects of different types grouped in a structure
- You need to execute many distinct and unrelated operations. It separates Operation from objects Structure
- New Operations have to be added without change in object structure
Related posts:

- 37,698
- 11
- 250
- 211