Interpreter
Represent each rule of a small language as a class, build sentences as trees of those objects, and evaluate the tree to get an answer.
Description
Interpreter is for small, domain-specific languages: discount rules, search filters, feature-flag targeting, alert conditions. Each grammar rule becomes a class. Terminal expressions are the leaves (total > 100, country = SE); non-terminal expressions combine others (and, or).
A sentence in the language is a tree of these objects, and evaluating it is one recursive call: each node evaluates its children and combines the results. Usually a small parser turns text into the tree; the pattern itself is about the tree and its evaluation.
Class diagram
Interpreter pattern class diagram
- Class DiscountService with + applies(rule, cart).
- Interface Rule with + evaluate(ctx): boolean.
- Class TotalAbove with + evaluate(ctx).
- Class CountryIs with + evaluate(ctx).
- Class And with + evaluate(ctx).
- Class Or with + evaluate(ctx).
- DiscountService evaluates Rule.
- TotalAbove implements Rule.
- CountryIs implements Rule.
- And implements Rule.
- Or implements Rule.
Sequence diagram
Interpreter pattern sequence diagram
- DiscountService → Or: evaluate(cart).
- Or → And: evaluate(cart).
- And → TotalAbove(100): evaluate(cart).
- And receives "true" back from TotalAbove(100).
- And → CountryIs(SE): evaluate(cart).
- And receives "true" back from CountryIs(SE).
- Or receives "true" back from And.
- DiscountService receives "true (first order not checked)" back from Or.
TypeScript example
A discount rule language built from expression objects: "(total > 100 and country = SE) or first order". Each node evaluates its children; the tree is the program.
// Interpreter: a tiny rule language for discounts, as a tree of expression objects.
interface Context {
total: number;
country: string;
firstOrder: boolean;
}
// Abstract expression
interface Rule {
evaluate(ctx: Context): boolean;
toString(): string;
}
// Terminal expressions
class TotalAbove implements Rule {
private readonly limit: number;
constructor(limit: number) {
this.limit = limit;
}
evaluate(ctx: Context): boolean {
return ctx.total > this.limit;
}
toString(): string {
return `total > ${this.limit}`;
}
}
class CountryIs implements Rule {
private readonly code: string;
constructor(code: string) {
this.code = code;
}
evaluate(ctx: Context): boolean {
return ctx.country === this.code;
}
toString(): string {
return `country = ${this.code}`;
}
}
class FirstOrder implements Rule {
evaluate(ctx: Context): boolean {
return ctx.firstOrder;
}
toString(): string {
return "first order";
}
}
// Non-terminal expressions: combine other rules
class And implements Rule {
private readonly parts: Rule[];
constructor(...parts: Rule[]) {
this.parts = parts;
}
evaluate(ctx: Context): boolean {
return this.parts.every((p) => p.evaluate(ctx));
}
toString(): string {
return `(${this.parts.join(" and ")})`;
}
}
class Or implements Rule {
private readonly parts: Rule[];
constructor(...parts: Rule[]) {
this.parts = parts;
}
evaluate(ctx: Context): boolean {
return this.parts.some((p) => p.evaluate(ctx));
}
toString(): string {
return `(${this.parts.join(" or ")})`;
}
}
export function demo(): string[] {
// "10% off when (total > 100 and country = SE) or first order"
// In a real system a small parser would build this tree from the rule text.
const rule: Rule = new Or(new And(new TotalAbove(100), new CountryIs("SE")), new FirstOrder());
const carts: Context[] = [
{ total: 150, country: "SE", firstOrder: false },
{ total: 150, country: "DE", firstOrder: false },
{ total: 20, country: "DE", firstOrder: true },
];
return [`rule: ${rule}`, ...carts.map((c) => `${c.total} ${c.country}${c.firstOrder ? " (new)" : ""}: ${rule.evaluate(c) ? "discount" : "no discount"}`)];
}When to use it
Use it when
- Users or admins need to write rules or filters that change without a code deploy.
- The language is small and stable: a handful of operators and value types.
- You want rules stored as data (in a database or config) and evaluated safely, without running arbitrary code.
Avoid it when
- The language is large or keeps growing. Use a parser generator, an existing expression language such as JSONLogic or CEL, or a real scripting engine.
- Performance matters on large inputs. Tree-walking is slow compared with compiling rules.
- The rules are fixed and written by developers. Plain code is simpler.
Pitfalls
- Grammar creep: every new requirement adds a class, until you've built a poor programming language. Set a firm scope.
- Confusing error messages for users when a rule fails to parse. Invest in the parser's errors, not just the evaluator.
- Unbounded evaluation, such as deeply nested rules or regular expressions on user input. Limit depth and cost.
Alternatives
Existing expression language
Choose it when you need user-editable rules: JSONLogic, CEL or a rules engine save you from writing a language.
Composite
Choose it when you just need a tree of objects; Interpreter is Composite with an evaluate operation and a grammar.
Visitor
Choose it when you need several operations over the same expression tree: evaluate, print, validate, optimise.
Strategy
Choose it when you have a few fixed rules to pick from, not a language to combine them.