Search code examples
design-patternsvisitor-pattern

Why not overload the "visit" method in the Visitor Pattern?


Here's the context/sample code of the Visitor design pattern:

public interface Visitable{
    public void accept(Visitor v);
}

public class Book implements Visitable{
    public void accept(Visitor v){
        v.visit(this);
    }
    public void read() {}
    /**
    book stuff
    **/
}
public class Movie implements Visitable{
    public void accept(Visitor v){
        v.visit(this);
    }
    public void watch() {}
    /**
    movie stuff
    **/
}

public interface Visitor{
    public void visit(Book b);
    public void visit(Movie m);
}

public class Person implements Visitor{
    public void visit(Book b){
        b.read();
    }
    public void visit(Movie m){
        m.watch();
    }
}

My instructor says that it's not a good idea to overload the visit method and I should give a distinct name to each visit method that looks like the following. I'm not convinced by this idea. Can someone explain what's the downside of overloading the visit method?

public interface Visitor{
    public void visitBook(Book b);
    public void visitMovie(Movie m);
}

public class Person implements Visitor{
    public void visitBook(Book b){
        b.read();
    }
    public void visitMovie(Movie m){
        m.watch();
    }
}

Solution

  • John Vlissides's book Pattern Hatching (one of the GOF authors and his book is sometimes considered a supplement to Design Patterns) explains the advantages both both ways to implement Visitor.

    The reason he says using the different variable names is this:

    A more substantial advantage comes when there's a resonalbe default behavior, and subclasses tend to override just a few of the operations. When we overload, subclasses must override all of the functions; otherwise your friendly C++ compiler will probably complain that your selective overrides hide one or more of the base class operations. We get around this probelm when we give Visitor operations difference names. Subclasses can then redefine a subset of the operations with impunity. - Pattern Hatching p.36