Interpreter Pattern
Represent a small language as expression objects that evaluate their own meaning.
· Last updated: 2026-11-07 · 8 min read
Overview
You need items tagged article, or items tagged both video and captioned. Copy that condition into nested if statements at several call sites, and each new condition adds a place to edit. Instead, express the conditions and their combinations as objects.
The Interpreter pattern represents a language's expressions as objects, each implementing the evaluation of its expression. Rather than analyzing the condition's structure and evaluating it itself, the caller asks the expression object to evaluate. The rule language here consists of a terminal tag test and the AND and OR nodes that combine two expressions.
UML
HasTag, And and Or implement IExpr. And and Or refer to two child expressions and combine their results.
History
GoF cataloged Interpreter as a behavioral pattern in Design Patterns in 1994. A grammar representation carries operations that evaluate its meaning.1
Representing grammar rules directly as in-memory data structures and evaluating them inside the host language goes back to John McCarthy's 1960 paper on LISP S-expressions and the metacircular eval function.2 Object-oriented compilers and rule engines in Smalltalk and C++ recast those syntax nodes as classes carrying an Eval() method, which GoF later codified as the Interpreter pattern.
Why use it?
The main gain is that a composed rule can be stored and reused as a structure. Callers do nothing but evaluate the whole expression, and each expression decides the order in which its subexpressions are evaluated. A new condition comes down to one more expression object.
Yet the reach of this approach is narrow. The example includes no parser that reads a string and turns it into that grammar structure. If the grammar grows or input comes from outside, existing parser tooling is the better choice, and limits on expression size and depth deserve consideration too.
Example
Start with one expression that checks a tag.
using System;
using System.Collections.Generic;
using System.Linq;
IExpr rule = new HasTag("article");
Console.WriteLine(rule.Eval(new HashSet<string> { "article" }));
// Different expression kinds evaluate the same input to a boolean result.
interface IExpr { bool Eval(IReadOnlySet<string> tags); }
sealed record HasTag(string Tag) : IExpr
{
public bool Eval(IReadOnlySet<string> tags) => tags.Contains(Tag);
}
// Delegate to child expressions and own only the combination rule.
sealed record And(IExpr Left, IExpr Right) : IExpr
{
public bool Eval(IReadOnlySet<string> tags) => Left.Eval(tags) && Right.Eval(tags);
}
sealed record Or(IExpr Left, IExpr Right) : IExpr
{
public bool Eval(IReadOnlySet<string> tags) => Left.Eval(tags) || Right.Eval(tags);
}
TrueHasTag is the terminal expression. It tests set membership rather than executing a string as code. It sits at the leaves of the tree.
An extended example
Build article OR (video AND captioned) as an expression tree and evaluate three inputs.
A single tag test cannot express the whole requirement, “an article, or a video with captions.” Writing it as article OR (video AND captioned) makes the grouping visible. The outer Or connects the article test to the video condition, while its right-hand And groups video with captioned.
With the article tag, the left HasTag is true, so the whole expression is true. With only video, the left side is false and the right side lacks captioned, making the And false too. With both video and captioned, the two leaf tests are true, so the And returns true to the outer Or.
Each HasTag still tests just one tag. The larger rule is expressed by connecting existing expression objects under different parents. Read the constructor's parentheses as branches of a tree, then follow each child's Boolean result back to its parent.
using System;
using System.Collections.Generic;
using System.Linq;
IExpr rule = new Or(new HasTag("article"), new And(new HasTag("video"), new HasTag("captioned")));
foreach (var tags in new[]
{
new HashSet<string> { "article" },
new HashSet<string> { "video" },
new HashSet<string> { "video", "captioned" }
}) Console.WriteLine(rule.Eval(tags));
// Different expression kinds evaluate the same input to a boolean result.
interface IExpr { bool Eval(IReadOnlySet<string> tags); }
sealed record HasTag(string Tag) : IExpr
{
public bool Eval(IReadOnlySet<string> tags) => tags.Contains(Tag);
}
// Delegate to child expressions and own only the combination rule.
sealed record And(IExpr Left, IExpr Right) : IExpr
{
public bool Eval(IReadOnlySet<string> tags) => Left.Eval(tags) && Right.Eval(tags);
}
sealed record Or(IExpr Left, IExpr Right) : IExpr
{
public bool Eval(IReadOnlySet<string> tags) => Left.Eval(tags) || Right.Eval(tags);
}
True
False
TrueAnd and Or combine their child results. A video alone fails, while a captioned video passes. The expressions carry the decision; the caller only assembles the tree. This is a content-classification example, not an authorization system.
TypeScript example
Each rule becomes its own expression object: one checks a single tag, and another combines several rules with AND and OR. One rule, one object. Callers assemble an expression tree instead of rewriting a complex conditional, and the same eval() evaluates any tree they build.
// Different expression kinds evaluate the same input to a boolean result.
interface IExpr { eval(tags: ReadonlySet<string>): boolean; }
class HasTag implements IExpr {
constructor(private readonly tag: string) {}
eval(tags: ReadonlySet<string>): boolean { return tags.has(this.tag); }
}
// Delegate to child expressions and own only the combination rule.
class And implements IExpr {
constructor(private readonly left: IExpr, private readonly right: IExpr) {}
eval(tags: ReadonlySet<string>): boolean { return this.left.eval(tags) && this.right.eval(tags); }
}
class Or implements IExpr {
constructor(private readonly left: IExpr, private readonly right: IExpr) {}
eval(tags: ReadonlySet<string>): boolean { return this.left.eval(tags) || this.right.eval(tags); }
}
const rule: IExpr = new Or(new HasTag("article"), new And(new HasTag("video"), new HasTag("captioned")));
for (const tags of [["article"], ["video", "captioned"], ["video"]]) {
console.log(rule.eval(new Set(tags)));
}true
true
falseAND and OR skip the right operand when the left result already settles the answer. The example builds expressions directly as objects; it is not a string parser or an arbitrary-code evaluator.
Boundary with algebraic data types, Visitor, and scaling limits
When choosing how to model an expression tree, the decisive question is whether you add new grammar nodes more often than you add new operations over the tree. Putting Eval() inside each class (the GoF Interpreter style) makes adding a new Not node effortless. The moment you also need pretty-printing, static validation, cost estimation, and optimization over that same tree, however, every new pass forces you to edit every node class.
Whenever the grammar is closed and operations multiply, separating passes via the Visitor Pattern—or declaring the syntax tree as an algebraic data type (discriminated union) and reducing it with a recursive Fold—keeps each pass in one place.
GoF explicitly warned against scaling Interpreter to large grammars: once rules grow past a couple dozen productions, class definitions explode and operator precedence becomes unwieldy. Deep pointer-chasing across heap-allocated AST nodes also hurts CPU cache locality and consumes one call-stack frame per tree level, which is why production query and rule engines compile syntax trees into flat bytecode arrays or state machines.
Related reading
Footnotes
- Gamma, Helm, Johnson, Vlissides. Design Patterns (1994). Publisher record. Behavioral patterns, Interpreter. ↩
- John McCarthy, "Recursive Functions of Symbolic Expressions and Their Computation by Machine, Part I," Communications of the ACM 3(4), 1960, pp. 184–195. DOI. ↩