2 ms·
There must be some confusion here. Your first paragraph describes what code looks like when you don't use the visitor pattern. Just to be explicit, here's the
by munificent 11y ago
There must be some confusion here. Your first paragraph describes what code looks like when you don't use the visitor pattern.
Just to be explicit, here's the kind of code I think you're describing (using some vague Java-esque pseudo-code):
interface Expression {
String prettyPrint();
int evaluate();
}
class Plus extends Expression {
Expression left, right;
String prettyPrint() {
return left.prettyPrint() + " + " + right.prettyPrint();
}
int evaluate() {
return left.evaluate() + right.evaluate();
}
}
class Number extends Expression {
int value;
String prettyPrint() {
return value.toString();
}
int evaluate() {
return value;
}
}
This is vanilla OOP code. You have all of the operations on a class directly on that class. Like you note, pretty printing and evaluating are mixed together. With something like an AST, it doesn't scale and gets gross.
Here's the AST classes supporting visitor pattern:
interface Expression {
String prettyPrint();
int evaluate();
T accept<T>(Visitor<T> visitor);
}
class Plus extends Expression {
Expression left, right;
T accept<T>(Visitor<T> visitor) { return visitor.visitPlus(this); }
}
class Number extends Expression {
int value;
T accept<T>(Visitor<T> visitor) { return visitor.visitNumber(this); }
}
interface Visitor<T> {
T visitPlus(Plus plus);
T visitNumber(Number number);
}
These are now pure data classes, like we want. The only extra bit is the visitor pattern itself.
Now we can separate out our concerns. Here's pretty-printing:
class PrettyPrintVisitor extends Visitor<String> {
String visitPlus(Plus plus) {
return plus.left.accept(this) + " + " + plus.right.accept(this);
}
String visitNumber(Number number) {
return number.value.toString();
}
}
And here's evaluating:
class EvalVisitor extends Visitor<int> {
int visitPlus(Plus plus) {
return plus.left.accept(this) + plus.right.accept(this);
}
int visitNumber(Number number) {
return number.value;
}
}
> I'm going to have a single AST pretty printing function that handles all the cases, a code generating function that handles all the cases and so on.
This is exactly what visitor gives you except replace "function" with "class".
> If someone adds a case, they will just have to add them to half a dozen functions.
They'll have to remember to do that. The visitor pattern makes it a compile error to forget to do that.
I also find the pattern scales up better than doing all of the type tests inside a single enormous function. I like having a separate method per AST type.