Search code examples
javadesign-patternsvisitor-pattern

Is it mandatory for the visit methods to return void in the Visitor Pattern?


This is the Java example of the visitor pattern in wikipedia:

These two interfaces are at the core of the pattern:

interface CarElement {
    void accept(CarElementVisitor visitor);
}

interface CarElementVisitor {
    void visit(Body body);
    void visit(Car car);
    void visit(Engine engine);
    void visit(Wheel wheel);
}

My question is:

Is it mandatory for the methods in these interfaces to return void or could they return other results?

In the example in wikipedia one of visitors is CarElementPrintVisitor. In each its methods writing to console is happen.

class CarElementPrintVisitor implements CarElementVisitor {
    @Override
    public void visit(Body body) {
        System.out.println("Visiting body");
    }
    ..
}

But lets say I don't want to write to console, lets say I want to receive String from visit methods, collect all that String, process them somehow and then write to file. For this I could use such interfaces:

interface CarElement {
    String accept(CarElementVisitor visitor);
}

interface CarElementVisitor {
    String visit(Body body);
    String visit(Car car);
    String visit(Engine engine);
    String visit(Wheel wheel);
}

So:

  • Why I souldn't do that?
  • Is it mondatory for methods in interfaces to be void methods in Visitor Pattern?

Solution

  • I would be particularly cautious about returning String from each method, as that can quickly lead to stringly-typed programming.

    But it is not mandatory for interface methods in the Visitor Pattern to return void. In fact, you can make the Visitor Pattern even more flexible (and type-safe) than the example in the OP by implementing a generic return type.

    Obviously the Visitor Pattern does require every visit method to return the same type, since all results are funneled through the accept method. This is perhaps why void is more typical: visiting diverse elements may not produce a common result.