Consider the following visitor for a simple language interpreter.
public interface Visitor{
void visit( VarStat vs);
void visit( Ident i);
void visit( IntLiteral a);
void visit( Sum s);
}
For completeness I add some code that gives necessary implementation details (you can skip and read directly the question).
public interface Visitable{
void accept( Visitor v);
}
public class VarStat implements Visitable{
Ident i;
Exp e;
public VarStat(Ident id, Exp ex){
i = id;
e = ex;
}
public Ident getIdent() { return i; }
public Exp getExp() { return e; }
@Override
public void accept( Visitor v){
v.visit( this);
}
}
public interface Exp extends Visitable{
}
public class Ident implements Exp{
@Override
public void accept( Visitor v){
v.visit( this);
}
}
a var statement is defined like that:
VarStat ::== var Ident = Exp;
Exp ::== Exp + Exp | IntLiteral | Ident
IntLiteral ::== [0-9]{0,8}
Ident ::== [a-zA-Z]+
a valid language instance
var x = x+y+4;
An abstract way to represent the VarStat
node is the following:
. _____VarStat _____
. / / | \ \
. / / | \ \
. / / | \ \
. "var" Ident "=" Exp ";"
The Question
The usual VisitorPattern application would be
void visit( VarStat vs){
vs.getIdent().accept( this);
vs.getExp().accept( this);
//...
}
however, since I know "Ident" is of type Ident
a possible optimization is
void visit( VarStat vs){
visit( vs.getIdent());
vs.getExp().accept( this);
//...
}
That would skip 2 method calls improving the performance (actually it gives a nice boost in my scenario).
Is that considered a design error that could lead to future problems?