For AI agents: the complete documentation index is available at https://nhanbe.id.vn/llms.txt, the full documentation bundle is available at https://nhanbe.id.vn/llms-full.txt, and this page is available as Markdown at https://nhanbe.id.vn/design-patterns/behavioral/interpreter.md.

Define a grammar and an interpreter to evaluate expressions in that language. You need a small, stable language for rules or filters. Expression

Interpreter

Overview

Define a grammar and an interpreter to evaluate expressions in that language.

When to use

  • You need a small, stable language for rules or filters.
  • Expressions are simple and frequent.

Java example

interface Expression {
    boolean interpret(String context);
}

class ContainsExpression implements Expression {
    private final String token;
    ContainsExpression(String token) { this.token = token; }
    public boolean interpret(String context) {
        return context.contains(token);
    }
}

TypeScript example

interface Expression {
  interpret(context: string): boolean;
}

class ContainsExpression implements Expression {
  constructor(private token: string) {}
  interpret(context: string): boolean {
    return context.includes(this.token);
  }
}

Pros and cons

Pros:

  • Easy to extend grammar with new expressions.
  • Clear representation of rules.

Cons:

  • Can become complex for large grammars.
  • Performance can degrade with many nodes.

Common pitfalls

  • Using Interpreter for complex DSLs.
  • Skipping caching for repeated evaluations.