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)

CoachSpring contextWodControllerMovement 10 burpeesWodParserRepeat 3 xSequence +TallyMovement 15 air-squats

Participants

  • 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

← Interpreter · Run it