When implementing the Visitor Pattern, is it a bad idea to add additional parameters to the Accept and Visit methods? I have never seen any examples that do this but no mention of it being a bad idea either.
I would like to use this pattern in my domain model however additional parameters are required along with the entity itself.
eg -
public interface ISomethingVisitor
{
void Visit(Foo foo, int p1, int p2);
}
public interface ISomethingVisitable
{
void Accept(ISomethingVisitor visitor, int p1, int p2);
}
I'd say it's a bad idea. It might work fine for this visitor, but what happens when another visitor requires more/different parameters? If p1
, p2
don't change, you can give them to the visitor at construction:
public class MyVisitor : ISomethingVisitor
{
private int p1;
private int p2;
public MyVisitor(int p1, int p2)
{
_p1 = p1;
_p2 = p2;
}
public void Visit(Foo foo)
{
//got access to _p1, _p2 here
}
}
I'm doing something similar to this, but with Java. I'm facing the same issue where I want to pass some 'visit context' information to the visit, but my issue is that the 'Visitor' is stateless so only one visitor is created up front to service all threads (ie: all information will have to come through paramaters). I don't want to get into the business of thread local vars.
So, to the design of your interface, I'd suggest the following:
public interface ISomethingVisitor
{
void Visit(Foo foo, VisitOptions params);
}
public interface ISomethingVisitable
{
void Accept(ISomethingVisitor visitor, VisitOptions params);
}
In this way, you can define your VisitOptions params with 2 fields: p1
and p2
, and if you want to add some paramaters later, no problem by adding those to your VisitOptions class...any existing code will just ignore they exist. You run into problems if you modify the VisitOptions by changing/removing parameters, but that's typical backwards-compatibility concerns.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With