Method naming in visitor design pattern

Viewed 1258

Here's the context/sample code of 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 no a good idea to overload 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 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();
    }
}
4 Answers

Honestly, it's just old people speaking. With an IDE, these days, going out of your way to name something:

class Visitor {
    public void VisitElementA(ElementA a);
    public void VisitElementB(ElementB b);
}

Is just redundant and a waste of precious horizontal space. You can easily and remorselessly just press whatever key combo tells your ide to give you a popup with all the posibile input types.

It's doubly pointless when virtually all implementations of visiotrs end up looking like this anyway:

class VisitableExample implements Visitable {

    public void accept(Visitor v) {
         v.visit(this);
    }

}
Related