Cheatsheet
Interpreter
Intent
For a small language, represent each rule of its grammar with a class; a sentence becomes a tree of those objects, and each one knows how to evaluate itself.
Structure (UML)
classDiagram
direction LR
class WodController {
<<Client>>
+totals(WodRequest req) Totals
}
class WodParser {
<<Client>>
+parse(String text) WodExpression
}
class Tally {
<<Context>>
~add(movement, n)
+totals() Map~String, Integer~
+reps() int
}
class WodExpression {
<<AbstractExpression>>
+interpret(Tally tally, long factor)
}
class Movement {
<<TerminalExpression>>
+interpret(Tally tally, long factor)
}
class Sequence {
<<NonterminalExpression>>
+interpret(Tally tally, long factor)
}
class Repeat {
<<NonterminalExpression>>
+interpret(Tally tally, long factor)
}
WodController --> WodParser
WodController ..> Tally : creates
WodParser ..> WodExpression : builds
WodExpression <|.. Movement
WodExpression <|.. Sequence
WodExpression <|.. Repeat
Sequence o-- WodExpression : parts
Repeat o-- WodExpression : bodyParticipants
- AbstractExpression (WodExpression), the interpret() operation every rule shares
- TerminalExpression (Movement), a rule that contains no others, like "10 burpees"
- NonterminalExpression (Sequence, Repeat), rules that contain other expressions, like "a + b" or "3 x ( … )"
- Context (Tally), where the expressions leave the result
- Client (WodController, with WodParser), builds the tree and asks it to interpret itself
WodInterpreterTest.java
WodExpression wod = parser.parse("2 x (3 x (5 pull-ups) + 10 burpees)");
Tally tally = new Tally();
wod.interpret(tally, 1);
assertThat(tally.totals()).containsExactly(Map.entry("pull-ups", 30), Map.entry("burpees", 20));Pros
- Each rule is a small class, easy to read and test
- Adding a new rule is adding a class (and a case in the parser)
- It works the same at any depth, because the tree walks itself
Cons
- With big grammars, that's a lot of classes; there a parser generator like ANTLR pays off
- A new operation (like validating or printing) means touching every class, unless you use a switch over the sealed type or a Visitor
- Walking a tree of objects is slower than compiled code; SpEL, for example, has a mode that compiles hot expressions to bytecode