Simple definition#
The Interpreter pattern defines a class for each rule of a small language’s grammar. A sentence in the language is parsed into a tree of these objects (an abstract syntax tree, AST), and calling interpret(context) on the root evaluates it recursively.
GoF intent: “Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language.”
The problem#
Product managers want to enable features for some users without a code release:
plan = pro and not country in [US, CA] or beta = true
Hard-coding each rule in Java requires a deployment for every change. Storing rules as data needs a way to represent and evaluate them safely, without eval or scripting engines with full system access.
Real-world analogy#
Musical notation. A score is a sentence in a language with a grammar (notes, rests, bars). A musician interprets it to produce sound, the same score for every orchestra.
Structure#
- Abstract expression (
Rule) — declaresinterpret(context). - Terminal expressions (
Equals,In) — leaves of the tree, evaluated directly against the context. - Nonterminal expressions (
And,Or,Not) — contain sub-expressions and combine their results. - Context — the input (
Map<String, String>of user attributes). - Client / parser — builds the AST from text.
classDiagram
direction TB
class Rule {
<<sealed interface>>
+interpret(Map) boolean
}
class Or {
left
right
}
class And {
left
right
}
class Not {
inner
}
class Equals {
name
value
}
class In {
name
values
}
Rule <|.. Or
Rule <|.. And
Rule <|.. Not
Rule <|.. Equals
Rule <|.. In
Or o--> Rule
And o--> Rule
Not o--> RuleThe structure is a Composite: nonterminals are composites, terminals are leaves.
Java implementation#
The code is in examples/java/src/hub/patterns/interpreter/InterpreterDemo.java.
Grammar as sealed records#
/**
* Grammar of a tiny feature-flag rule language:
* expr := term ("or" term)*
* term := factor ("and" factor)*
* factor := "not" factor | "(" expr ")" | NAME "=" VALUE | NAME "in" "[" VALUE ("," VALUE)* "]"
* Each rule of the grammar becomes one class (record) with an interpret method.
*/
sealed interface Rule permits Or, And, Not, Equals, In {
boolean interpret(Map<String, String> context);
}
record Or(Rule left, Rule right) implements Rule {
public boolean interpret(Map<String, String> ctx) { return left.interpret(ctx) || right.interpret(ctx); }
}
record And(Rule left, Rule right) implements Rule {
public boolean interpret(Map<String, String> ctx) { return left.interpret(ctx) && right.interpret(ctx); }
}
record Not(Rule inner) implements Rule {
public boolean interpret(Map<String, String> ctx) { return !inner.interpret(ctx); }
}
record Equals(String name, String value) implements Rule {
public boolean interpret(Map<String, String> ctx) { return value.equals(ctx.get(name)); }
}
record In(String name, Set<String> values) implements Rule {
public boolean interpret(Map<String, String> ctx) { return values.contains(ctx.get(name)); }
}Parser#
/** Recursive-descent parser: builds the abstract syntax tree. Not part of GoF Interpreter, but always needed. */
final class RuleParser {
private final List<String> tokens;
private int pos;
private RuleParser(String source) {
this.tokens = new ArrayList<>();
for (String t : source.replace("(", " ( ").replace(")", " ) ").replace("[", " [ ")
.replace("]", " ] ").replace(",", " , ").replace("=", " = ").trim().split("\\s+")) {
tokens.add(t);
}
}
static Rule parse(String source) {
RuleParser p = new RuleParser(source);
Rule rule = p.expr();
if (p.pos != p.tokens.size()) {
throw new IllegalArgumentException("Unexpected token '" + p.tokens.get(p.pos) + "'");
}
return rule;
}
private Rule expr() {
Rule left = term();
while (accept("or")) { left = new Or(left, term()); }
return left;
}
private Rule term() {
Rule left = factor();
while (accept("and")) { left = new And(left, factor()); }
return left;
}
private Rule factor() {
if (accept("not")) { return new Not(factor()); }
if (accept("(")) { Rule r = expr(); expect(")"); return r; }
String name = next();
if (accept("=")) { return new Equals(name, next()); }
expect("in");
expect("[");
Set<String> values = new java.util.LinkedHashSet<>();
do { values.add(next()); } while (accept(","));
expect("]");
return new In(name, values);
}
private boolean accept(String t) {
if (pos < tokens.size() && tokens.get(pos).equals(t)) { pos++; return true; }
return false;
}
private void expect(String t) {
if (!accept(t)) { throw new IllegalArgumentException("Expected '" + t + "' at token " + pos); }
}
private String next() {
if (pos >= tokens.size()) { throw new IllegalArgumentException("Unexpected end of rule"); }
return tokens.get(pos++);
}
}GoF’s Interpreter does not cover parsing, but you always need one. A recursive-descent parser has one method per grammar rule (expr, term, factor). Operator precedence falls out of the nesting: and binds tighter than or because term is called from expr.
AST: Or[left=And[left=Equals[name=plan, value=pro], right=Not[inner=In[name=country, values=[US, CA]]]], right=Equals[name=beta, value=true]]
ana -> true
bob -> false
cy -> true
dee -> false
Invalid rule: Unexpected end of ruleflowchart TD
OR[Or] --> AND[And]
OR --> B["Equals beta = true"]
AND --> P["Equals plan = pro"]
AND --> NOT[Not]
NOT --> IN["In country [US, CA]"]When a DSL is worth it#
| Situation | Better choice |
|---|---|
| A few simple, stable rules | Plain Java code |
| Rules change often and are edited by non-developers, with a small grammar | Interpreter (this pattern) |
| Rich expressions and existing tooling are acceptable | An embedded language: SpEL, MVEL, CEL, JSON Logic |
| Large grammar, performance-critical | A parser generator (ANTLR) and compilation to bytecode or a VM |
Interpreter and Visitor#
Putting interpret in every node is fine for one operation. If you also need to pretty-print, validate and optimise rules, each operation adds a method to every class. Two alternatives:
- Visitor: keep the nodes as data and put each operation in a visitor.
- Sealed interfaces and pattern matching (Java 21): write
switch (rule) { case And(var l, var r) -> ... }in a separate class per operation; the compiler checks exhaustiveness.
Advantages and disadvantages#
| Advantages | Disadvantages |
|---|---|
| Easy to change and extend a small grammar: one class per rule | Complex grammars produce many classes and are hard to maintain |
| Rules become data that can be stored, versioned and edited | Tree-walking is slow compared with compiled code |
| Safe: only operations the grammar allows can run | Needs a parser, error messages and tooling |
When to use it#
- A simple language that changes or is edited often: feature flags, pricing rules, search filters, validation rules, alert conditions.
- Efficiency is not critical, or results can be cached.
When not to use it#
- The grammar is large (use a parser generator) or performance-critical (compile).
- An existing expression language already fits and is safe for your inputs.
Common mistakes#
- Poor error messages (“syntax error”) that make rules impossible to fix for non-developers.
- Unbounded recursion on deeply nested input; limit depth for untrusted rules.
- Mixing evaluation with I/O inside terminal expressions, making rules slow and unpredictable.
Real-world uses#
java.util.regex.Patterncompiles a regular expression into a tree of node objects that match input.- Spring Expression Language (SpEL) parses expressions into an AST of
SpelNodes; see Spring Expression Language. - JPA Criteria and Spring Data
Specifications build query expression trees. java.text.MessageFormatand template engines interpret format strings.
Interview questions and answers#
What is the Interpreter pattern?
A behavioral pattern that represents each grammar rule of a small language as a class, builds sentences into an AST, and evaluates them by recursive interpret calls.
What are terminal and nonterminal expressions? Terminals are leaves evaluated directly (a comparison, a literal). Nonterminals combine sub-expressions (and, or, not).
Does the pattern include parsing? No. GoF assumes the AST exists; in practice you write a parser, often recursive descent.
When would you not use it? For complex grammars or performance-critical evaluation; use a parser generator or compile to code instead.
Summary#
- Interpreter turns a small grammar into classes and evaluates an AST recursively.
- It is a Composite with an
interpretoperation. - Pair it with a parser; parse once, evaluate many times.
- Prefer safe, purpose-built interpreters for user-editable rules.
Related topics#
- Composite Pattern
- Visitor Pattern
- Spring Expression Language
- Modern Java: records, sealed classes and pattern matching
References#
- Gamma, Helm, Johnson, Vlissides. Design Patterns. Addison-Wesley, 1994. Interpreter, p. 243.
- Robert Nystrom. Crafting Interpreters. Genever Benning, 2021. Chapters 5–7 (representing code, parsing, evaluating).