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

evaluatesDiscountService+ applies(rule, cart)«interface»Rule+ evaluate(ctx): booleanTotalAbove- limit: number+ evaluate(ctx)CountryIs- code: string+ evaluate(ctx)And- parts: Rule[]+ evaluate(ctx)Or- parts: Rule[]+ evaluate(ctx)

Interpreter pattern class diagram

  1. Class DiscountService with + applies(rule, cart).
  2. Interface Rule with + evaluate(ctx): boolean.
  3. Class TotalAbove with + evaluate(ctx).
  4. Class CountryIs with + evaluate(ctx).
  5. Class And with + evaluate(ctx).
  6. Class Or with + evaluate(ctx).
  7. DiscountService evaluates Rule.
  8. TotalAbove implements Rule.
  9. CountryIs implements Rule.
  10. And implements Rule.
  11. Or implements Rule.

Sequence diagram

DiscountServiceOrAndTotalAbove(100)CountryIs(SE)1. evaluate(cart)2. evaluate(cart)3. evaluate(cart)4. true5. evaluate(cart)6. true7. true8. true (first order not checked)

Interpreter pattern sequence diagram

  1. DiscountService → Or: evaluate(cart).
  2. Or → And: evaluate(cart).
  3. And → TotalAbove(100): evaluate(cart).
  4. And receives "true" back from TotalAbove(100).
  5. And → CountryIs(SE): evaluate(cart).
  6. And receives "true" back from CountryIs(SE).
  7. Or receives "true" back from And.
  8. 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.ts
// 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.