Design Patterns

Pattern 23 of 23, Behavioral family

Interpreter

Define the grammar of a small language and an interpreter that evaluates sentences in that language.

The problem

Your users need to enter rules such as (price + 3) * 2 or age > 18 AND country = "TN". Hard-coding every combination is impossible.

The solution

Represent each grammar rule with a class (number, variable, addition…). An expression becomes an abstract syntax tree (AST); each node knows how to evaluate itself, recursively.

The pattern in action

  • Client
  • Key role of the pattern
  • Object
  • Data or state
  1. We evaluate (x + 3) × 2: interpret() is called on the root of the tree.
  2. Each node first evaluates its children (recursion).
  3. Add (+) → Var x: interpret(ctx)
  4. A variable is resolved through the context.
  5. ctx { x: 5 } → Var x: 5
  6. Var x = 5 → Add (+): 5
  7. Add (+) → Num 3: interpret(ctx)
  8. Num 3 → Add (+): 3
  9. Add = 8 → Mul (×): 8
  10. Mul (×) → Num 2: interpret(ctx)
  11. Result: 16. Each grammar rule = a class that knows how to evaluate itself.

An analogy

A musician reading a score: each symbol has an interpretation rule, and the combination produces the melody.

When to use it

  • Simple DSLs: business rules, filters, formulas
  • Template engines, search expressions
  • Calculators, config mini-languages

Pros and cons

Pros

  • Grammar easy to extend (new rule = new class)
  • Each rule isolated and testable

Cons

  • Unsuited to complex grammars (prefer a parser generator: ANTLR…)
  • Limited performance on large trees

Implementations

The same example, written idiomatically in each language.

Interpreter in Python

interpreter.py 36 lines
from dataclasses import dataclass


class Expr:
    def interpret(self, ctx: dict) -> float: ...


@dataclass
class Num(Expr):
    v: float
    def interpret(self, ctx): return self.v


@dataclass
class Var(Expr):
    name: str
    def interpret(self, ctx): return ctx[self.name]


@dataclass
class Add(Expr):
    l: Expr
    r: Expr
    def interpret(self, ctx): return self.l.interpret(ctx) + self.r.interpret(ctx)


@dataclass
class Mul(Expr):
    l: Expr
    r: Expr
    def interpret(self, ctx): return self.l.interpret(ctx) * self.r.interpret(ctx)


# (x + 3) * 2
expr = Mul(Add(Var("x"), Num(3)), Num(2))
print(expr.interpret({"x": 5}))   # 16

Interpreter in TypeScript

interpreter.ts 22 lines
type Expr =
  | { kind: "num"; v: number }
  | { kind: "var"; name: string }
  | { kind: "add" | "mul"; l: Expr; r: Expr };

function interpret(e: Expr, ctx: Record<string, number>): number {
  switch (e.kind) {
    case "num": return e.v;
    case "var": return ctx[e.name];
    case "add": return interpret(e.l, ctx) + interpret(e.r, ctx);
    case "mul": return interpret(e.l, ctx) * interpret(e.r, ctx);
  }
}

// (x + 3) * 2
const expr: Expr = {
  kind: "mul",
  l: { kind: "add", l: { kind: "var", name: "x" }, r: { kind: "num", v: 3 } },
  r: { kind: "num", v: 2 },
};

interpret(expr, { x: 5 }); // 16

Interpreter in Java

interpreter.java 23 lines
sealed interface Expr {
    double interpret(Map<String, Double> ctx);
}

record Num(double v) implements Expr {
    public double interpret(Map<String, Double> ctx) { return v; }
}

record Var(String name) implements Expr {
    public double interpret(Map<String, Double> ctx) { return ctx.get(name); }
}

record Add(Expr l, Expr r) implements Expr {
    public double interpret(Map<String, Double> ctx) { return l.interpret(ctx) + r.interpret(ctx); }
}

record Mul(Expr l, Expr r) implements Expr {
    public double interpret(Map<String, Double> ctx) { return l.interpret(ctx) * r.interpret(ctx); }
}

// (x + 3) * 2
Expr e = new Mul(new Add(new Var("x"), new Num(3)), new Num(2));
e.interpret(Map.of("x", 5.0)); // 16.0

Interpreter in C#

interpreter.cs 18 lines
abstract record Expr;
record Num(double V) : Expr;
record Var(string Name) : Expr;
record Add(Expr L, Expr R) : Expr;
record Mul(Expr L, Expr R) : Expr;

static double Eval(Expr e, IReadOnlyDictionary<string, double> ctx) => e switch
{
    Num n => n.V,
    Var v => ctx[v.Name],
    Add a => Eval(a.L, ctx) + Eval(a.R, ctx),
    Mul m => Eval(m.L, ctx) * Eval(m.R, ctx),
    _ => throw new NotSupportedException()
};

// (x + 3) * 2
var expr = new Mul(new Add(new Var("x"), new Num(3)), new Num(2));
Eval(expr, new Dictionary<string, double> { ["x"] = 5 }); // 16

Interpreter in PHP

interpreter.php 35 lines
interface Expr { public function interpret(array $ctx): float; }

final class Num implements Expr
{
    public function __construct(private float $v) {}
    public function interpret(array $ctx): float { return $this->v; }
}

final class Variable implements Expr
{
    public function __construct(private string $name) {}
    public function interpret(array $ctx): float { return $ctx[$this->name]; }
}

final class Add implements Expr
{
    public function __construct(private Expr $l, private Expr $r) {}
    public function interpret(array $ctx): float
    {
        return $this->l->interpret($ctx) + $this->r->interpret($ctx);
    }
}

final class Mul implements Expr
{
    public function __construct(private Expr $l, private Expr $r) {}
    public function interpret(array $ctx): float
    {
        return $this->l->interpret($ctx) * $this->r->interpret($ctx);
    }
}

// (x + 3) * 2
$expr = new Mul(new Add(new Variable('x'), new Num(3)), new Num(2));
echo $expr->interpret(['x' => 5]); // 16

Interpreter in Go

interpreter.go 17 lines
type Expr interface {
    Eval(ctx map[string]float64) float64
}

type Num float64
type Var string
type Add struct{ L, R Expr }
type Mul struct{ L, R Expr }

func (n Num) Eval(map[string]float64) float64     { return float64(n) }
func (v Var) Eval(ctx map[string]float64) float64 { return ctx[string(v)] }
func (a Add) Eval(ctx map[string]float64) float64 { return a.L.Eval(ctx) + a.R.Eval(ctx) }
func (m Mul) Eval(ctx map[string]float64) float64 { return m.L.Eval(ctx) * m.R.Eval(ctx) }

// (x + 3) * 2
e := Mul{Add{Var("x"), Num(3)}, Num(2)}
fmt.Println(e.Eval(map[string]float64{"x": 5})) // 16

Frequently asked questions

What is the Interpreter design pattern?

Define the grammar of a small language and an interpreter that evaluates sentences in that language. Represent each grammar rule with a class (number, variable, addition…). An expression becomes an abstract syntax tree (AST); each node knows how to evaluate itself, recursively.

When should you use the Interpreter pattern?

Simple DSLs: business rules, filters, formulas; Template engines, search expressions; Calculators, config mini-languages.

What are the pros and cons of the Interpreter pattern?

Pros: Grammar easy to extend (new rule = new class); Each rule isolated and testable. Cons: Unsuited to complex grammars (prefer a parser generator: ANTLR…); Limited performance on large trees.