Interpreter Pattern

The Interpreter pattern gives every rule in a small grammar its own class, and each of those classes knows how to evaluate itself against a context. A rule is then a tree of those objects – an And holding a SeverityAtLeast and an Or, the Or holding two field comparisons – and running it means calling evaluate(context) on the root. This is the pattern behind every rule engine and every spreadsheet formula bar: the formula you type is not code that gets compiled, it is a tree of node objects that gets walked.

💡 Terminal expression = a leaf that reads the context and returns a verdict on its own, like severity >= HIGH. Non-terminal expression = a node holding child expressions and combining their verdicts, like And. Interpreter is those two kinds of class and nothing else.

Why this matters: Interpreter is the GoF pattern most likely to be over-applied, and a good interviewer is watching for that, because “write a little language” is almost never the right answer to a business problem. It is worth knowing anyway because the shape is what you need the moment the rules are supplied by someone who is not you – user-defined filters, discount campaigns, alert routing and spreadsheet formulas are all the same LLD problem. Two things get graded: that you reach for the tree only when the rules come from outside the codebase, and that you treat a user-supplied tree as untrusted input.


Prerequisites

  • Composite Pattern – Interpreter’s node tree is a Composite with one extra method, so get that recursion straight first
  • Specification Pattern – the single-purpose cousin, and the design to rule out before building a grammar

The Problem: the routing rule is a Java if statement

Here is the condition for an alert-routing rule, written the way it gets written the first time. One service, one on-call rotation, one if:

public class AlertRouter {

    public List<String> route(Alert alert) {
        List<String> targets = new ArrayList<>();

        // "page on-call if severity is high AND (service is payments OR region is EU)"
        if (alert.getSeverity() == Severity.HIGH
                && (alert.getService().equals("payments")
                    || alert.getRegion().startsWith("eu-"))) {
            targets.add("oncall-payments");
        }

        // ...then the checkout team asks for theirs, and the next team, and the
        // next, each one another hand-written if in this same method

        if (targets.isEmpty()) targets.add("alerts-firehose");
        return targets;
    }
}

Nothing is wrong with this on the day it is written. Then the requirement that was always coming arrives: operations staff must edit these conditions themselves, in a console, without waiting for a deploy. There are forty rules now, they change weekly, and the people changing them do not have a build setup.

  1. A rule change is a code change plus a release. Flipping one comparison means a commit, a review, a build and a deploy – hours to days for a condition somebody wanted changed in a minute – and the release carries whatever else is on mainline, so a one-word tweak inherits that afternoon’s risk.
  2. The condition is not data, so nothing can be done to it. It cannot be stored in a row beside the rule’s owner, and it cannot be diffed, so “what did this rule say last Tuesday when nobody got paged” has no answer short of reading git log against deploy times. It cannot be rendered in a UI, validated before it runs, or explained after it fires, because the condition does not exist as a thing – it is three branches partway through a method.
  3. The obvious shortcut is worse than the problem. Move the condition into config as the string severity == 'HIGH' && (service == 'payments' || region == 'eu-west-1'), hand it to Java’s ScriptEngine, Groovy, or Python’s eval, and you ship two holes. The first is arbitrary code execution: with the host-language interop those engines enable by default, a rule string reaches Runtime.getRuntime().exec, reads environment variables and opens sockets, so the rule editor is a remote shell holding the service’s credentials. The second is unbounded evaluation: while (true) or a backtracking regex hangs the routing thread, and eval has no timeout, no instruction budget and no safe interrupt. Nor can you check a stored rule is valid without executing it.

What you want is a condition that is an object graph: storable, validated on save, drawable in a form, walked under limits you set.


Class Diagram

classDiagram
    class Expression {
        <<interface>>
        +evaluate(Context) boolean
    }
    class Context {
        <<interface>>
        +get(String field) Optional~String~
        +charge()
    }
    class FieldEquals {
        -String field
        -String expected
    }
    class FieldIn {
        -Set~String~ allowed
    }
    class And {
        -List~Expression~ children
    }
    class RuleCompiler {
        -int maxDepth
        +compile(JsonNode) Expression
    }

    Expression <|.. FieldEquals
    Expression <|.. FieldIn
    Expression <|.. SeverityAtLeast
    Expression <|.. And
    Expression <|.. Or
    Expression <|.. Not
    And o-- Expression
    Or o-- Expression
    Not o-- Expression
    RuleCompiler --> Expression
    Expression --> Context

Two things are worth pointing at. And o-- Expression aggregates the very interface And implements, which is the Composite recursion and the reason a rule nests arbitrarily. And Expression --> Context is a parameter relation, not a field: no node stores anything about the event, so one compiled tree is immutable, reusable across events and safe to share between threads.

💡 AST (abstract syntax tree) = the tree of node objects a rule becomes, with the syntax stripped out. Interpreter gives the AST nodes an evaluate method; Visitor keeps them dumb and puts the operations elsewhere.


Real-World Example: Alert Routing Rules

The stored rule, as the console saves it and the database holds it – a row in a table, not a source file:

{ "op": "and", "children": [
    { "op": "severity_at_least", "value": "HIGH" },
    { "op": "or", "children": [
        { "op": "eq", "field": "service", "value": "payments" },
        { "op": "in", "field": "region", "values": ["eu-west-1", "eu-central-1"] }
    ] } ] }

The input is structured, not text, and that is a deliberate choice. The textbook version of this pattern arrives with a parser attached, and the parser is the part that eats your hour. An explicit op per node means no lexer, no precedence table and no argument about whether a AND b OR c groups left or right – the nesting is the tree. It also diffs cleanly in an audit log, and a rule editor renders it directly.

// ---- Context: a map-like, read-only view of one event, plus the node budget ----
public interface Context {
    Optional<String> get(String field);   // empty when absent; absent is not ""
    void charge();     // once per node entered. EventContext implements it as
}                      // if (--remaining < 0) throw new RuleBudgetExceeded();

public interface Expression {       // every rule in the grammar is one of these
    boolean evaluate(Context ctx);
}

// ---- Terminals: one class per rule that reads the event ----
public final class FieldEquals implements Expression {
    private final String field, expected;
    public FieldEquals(String f, String e) { field = requireNonNull(f); expected = requireNonNull(e); }
    @Override public boolean evaluate(Context ctx) {
        ctx.charge();
        // A missing field is false, never an exception: events are heterogeneous
        // and one absent field must not abort the whole routing pass.
        return ctx.get(field).map(expected::equals).orElse(false);
    }
    @Override public String toString() { return field + " == " + expected; }
}                         // every node has one: the trace line and editor label

// FieldIn mirrors it over a Set.copyOf allowlist and allowed::contains -- Set,
// not List, so membership is O(1) per evaluation. The Python tab spells it out.

public final class SeverityAtLeast implements Expression {
    private final Severity floor;      // Severity is an enum with rank(), so the
    public SeverityAtLeast(Severity f) { floor = requireNonNull(f); }  // ordering
    @Override public boolean evaluate(Context ctx) {   // lives there and a rule
        ctx.charge();                   // cannot reorder or restring severities
        return ctx.get("severity").flatMap(Severity::parse)   // unknown -> empty
                  .filter(a -> a.rank() >= floor.rank()).isPresent();
    }
}

// ---- Non-terminals: hold children, combine verdicts, short-circuit ----
public final class And implements Expression {
    private final List<Expression> children;
    public And(List<Expression> kids) { children = List.copyOf(kids); }
    @Override public boolean evaluate(Context ctx) {
        ctx.charge();
        for (Expression child : children)
            if (!child.evaluate(ctx)) return false;    // stop at the first false
        return true;   // an empty And is vacuously true; the compiler rejects one
    }
}

// Or is the same class with the early return inverted -- `if (child.evaluate(ctx))
// return true;` inside the loop, `return false;` after -- so it stops at the
// first true and an empty Or is vacuously false. Not negates a single child.

// ---- Compiling the stored document into a tree, with the structural guards ----
public final class RuleCompiler {
    private static final int MAX_DEPTH = 8, MAX_NODES = 100;
    // An allowlist, so a renamed or internal field cannot be referenced at all.
    private static final Set<String> KNOWN_FIELDS =
            Set.of("service", "region", "severity", "environment", "alarm_name");
    private int nodeCount;

    /** Input is already-parsed JSON. There is no lexer anywhere in this class. */
    public static Expression compile(JsonNode root) { return new RuleCompiler().node(root, 1); }

    private Expression node(JsonNode json, int depth) {
        if (depth > MAX_DEPTH) throw new InvalidRuleException("too deep");
        if (++nodeCount > MAX_NODES) throw new InvalidRuleException("too many nodes");
        switch (json.path("op").asText("")) {
            case "and": return new And(children(json, depth));
            case "or":  return new Or(children(json, depth));
            case "not": return new Not(node(json.required("child"), depth + 1));
            case "eq":  return new FieldEquals(field(json), json.required("value").asText());
            case "in":  return new FieldIn(field(json), texts(json.required("values")));
            case "severity_at_least":
                return new SeverityAtLeast(severity(json.required("value").asText()));
            default: throw new InvalidRuleException("unknown op");
        }
    }

    private List<Expression> children(JsonNode json, int depth) {
        List<Expression> out = new ArrayList<>();
        for (JsonNode kid : json.required("children")) out.add(node(kid, depth + 1));
        // Reject the empty case, or a rule saved with no conditions silently
        // becomes "match everything" on its author's very first save.
        if (out.isEmpty()) throw new InvalidRuleException("needs children");
        return out;
    }   // field() throws unless KNOWN_FIELDS holds the name; texts() and
}       // severity() are the same shape -- parse, reject, never default.
from dataclasses import dataclass

# Context is as in the Java tab: get(field) returns None for an absent field,
# never "", and charge() raises once the per-event node budget runs out.

@dataclass(frozen=True, slots=True)     # frozen: a compiled rule is immutable
class FieldIn:                          # a terminal
    field: str
    allowed: frozenset[str]             # hashable, so the node stays frozen
    def evaluate(self, ctx) -> bool:
        ctx.charge()
        return ctx.get(self.field) in self.allowed

@dataclass(frozen=True, slots=True)
class And:                              # a non-terminal
    children: tuple
    def evaluate(self, ctx) -> bool:
        ctx.charge()
        # all() and any() short-circuit over a generator, which is exactly the
        # Java for-loop-with-early-return. Or is any(); Not negates one child.
        return all(child.evaluate(ctx) for child in self.children)

# ---- The idiomatic Python form: a tuple AST and one match statement ----------
# A class per rule is the GoF shape, but in Python the grammar fits in one
# function and 3.10 pattern matching does the dispatch the virtual call did.
# The trade: nothing is left to hang a UI label or an explanation on.
RANK = {"INFO": 0, "WARNING": 1, "HIGH": 2, "CRITICAL": 3}

def evaluate(node: tuple, ctx) -> bool:
    ctx.charge()
    match node:
        case ("and", *kids):         return all(evaluate(k, ctx) for k in kids)
        case ("or", *kids):          return any(evaluate(k, ctx) for k in kids)
        case ("not", kid):           return not evaluate(kid, ctx)
        case ("eq", field, value):   return ctx.get(field) == value
        case ("in", field, allowed): return ctx.get(field) in allowed
        case ("sev", floor):
            return RANK.get((ctx.get("severity") or "").upper(), -1) >= RANK[floor]
        case _:                      raise InvalidRule(node)
#include <memory>
#include <optional>
#include <string>
#include <vector>

class Context {        // both const: evaluation must not mutate the event, and
public:                // the counter behind charge() is a mutable member --
    virtual ~Context() = default;              // bookkeeping, not real state
    virtual std::optional<std::string> get(const std::string&) const = 0;
    virtual void charge() const = 0;
};

class Expression {
public:
    virtual ~Expression() = default;
    virtual bool evaluate(const Context& ctx) const = 0;
};
using ExprPtr = std::unique_ptr<Expression>;

// A terminal charges, then reads its field and treats nullopt as false:
//     auto v = ctx.get(field_); return v.has_value() && *v == expected_;

// Children owned by value, so the root owns the whole tree's memory. Or is the
// same class with the early return inverted; Not holds a single ExprPtr.
class And : public Expression {
    std::vector<ExprPtr> children_;
public:
    explicit And(std::vector<ExprPtr> kids) : children_(std::move(kids)) {}
    bool evaluate(const Context& ctx) const override {
        ctx.charge();
        for (const auto& child : children_)
            if (!child->evaluate(ctx)) return false;       // short-circuit
        return true;
    }
};

// unique_ptr children mean ~And recurses into ~And, so a pathologically deep
// tree overflows the stack on destruction as well as on evaluation. Capping
// depth in the compiler protects both.

The router compiles each stored rule once, then gives every evaluation a fresh EventContext with its own node budget inside its own try/catch, so one pathological rule cannot silence the other thirty-nine, and falls back to a firehose target when nothing matches.


The tree is data, and that is the entire payoff

Everything the if-statement version could not do was blocked by one fact: the condition was not a thing. Make it an object graph and four capabilities arrive at once.

  1. Store it. The rule is a JSON column beside its owner and last-edited timestamp, so “who changed this, and when” is a query.
  2. Validate it before it runs. RuleCompiler rejects an unknown field or operator, a depth over eight and a node count over a hundred at save time – what eval structurally cannot offer.
  3. Show it. toString() renders the tree for a trace; a recursive walk renders it as nested form controls, so non-engineers edit AND/OR groups in a UI.
  4. Explain it. The capability that sells the design, and it costs one method on Context.

Add void record(Expression node, boolean verdict) to Context and have every node name its verdict before returning it. An ExplainingContext then decorates the real one, appending each node and its verdict to a list while get and charge delegate, so tracing is opt-in per evaluation. One alert through the stored rule above explains itself from data: severity >= HIGH true, service == payments false, region in [eu-west-1, eu-central-1] true, root true. Because And and Or short-circuit, the last terminal recorded before a non-terminal reports is the node that decided the outcome – here, the region check. Not flips the sign, so the renderer walks the recorded path rather than taking the last line.

Now the honest costs, because an interviewer will ask and there are three.

It is slow, and the slowness is structural. An interpreted walk runs one to two orders of magnitude behind equivalent compiled code – a property of the mechanism, not a benchmark. Every node is a virtual call the JIT cannot inline because the call site is megamorphic, every field read is a hash lookup, and the tree is pointer-chasing through cold cache lines. Fine for forty rules per alert; not fine in a per-row loop over ten million rows.

Recursion means the stack is your depth limit. A deliberately deep tree is a StackOverflowError, and the C++ tab shows the nastier version where even destroying the tree recurses. That is why MAX_DEPTH lives in the compiler: once the tree exists, it is too late.

You have invented a language, so it needs documentation, a version number and a migration story. The day region becomes availability_zone, every stored rule naming region silently never matches – no error, just a rotation that stops getting paged. A grammar with users is a public API.

So the decision rule: use Interpreter when the rules change more often than the code ships and non-engineers own them. Do not use it when the rules are stable and owned by the team that owns the code, because then they are just code, and Specification composes them with none of this machinery.

Compiling the tree once

The standard optimisation is to stop interpreting and start compiling: walk the tree once, fold it into a closure, keep the closure. And compiles to ctx -> first.test(ctx) && second.test(ctx) over its children’s already-compiled closures, so the root returns one Predicate<Context> you cache against the rule id and invalidate on edit. The per-node overhead is then paid once per rule version instead of once per event.

That is also the boundary: once you are caching compiled forms and reordering cheap predicates ahead of expensive ones you are writing an expression compiler, and mature ones exist – Spring Expression Language, MVEL, JSONLogic, and CEL, which computes a static cost bound before evaluating. Writing your own past this line needs a better reason than “ours is simpler”.


Interpreter vs Visitor vs Composite vs Specification vs Strategy

All five put behaviour behind an interface and four involve a tree, which is why they blur. What separates them is where the tree came from and what you do to it.

Pattern Intent Tell
Interpreter A grammar as one class per rule, evaluated against a context The tree came from outside the codebase – a database row, a config file, a rule editor
Composite Treat one node and a group of nodes uniformly Same tree, no context and no verdict – the operation is size(), not evaluate(ctx)
Visitor Add operations over a settled node set without editing the nodes What multiplies is operations – evaluate, print, type-check – not node types
Specification Compose typed boolean predicates with and, or, not Written in code and checked by the compiler: no grammar, no parser
Strategy Swap one algorithm behind one interface A single object with no children – nothing to walk

Interpreter is Composite with evaluate(context) added to the node interface; that is the whole structural difference, and saying so beats reciting two intents. Visitor is what you extract when operations over the same tree outgrow evaluation.

The comparison that decides a design is Interpreter versus Specification. Specification is usually the better choice, and Interpreter earns its place only when the rules come from outside the codebase. If engineers author the rules, write typed predicates and compose them – highSeverity.and(payments.or(euRegion)) – for compile-time field checking and ordinary unit tests, with no parser, allowlist, depth limit or migration story. The instant a non-engineer edits a rule through a UI, every one of those guarantees must be rebuilt as runtime validation over stored data – which is what Interpreter is.


When to Use vs When to Avoid

Use Interpreter When Avoid When
Non-engineers author and edit the rules through a UI or config table The rules live in code and the code’s owners own them – use Specification
Rules change more often than the service ships The condition is one swappable algorithm – use Strategy
You must store, diff, audit and version what a rule said when it fired Evaluation sits in a hot per-row loop where the overhead shows
You need to explain a decision afterwards, from stored data The grammar is acquiring variables, arithmetic or loops
The vocabulary is small and fixed – a dozen operators over known fields There is one production and always will be – use a predicate

The characteristic failure mode is the accidental programming language. It starts as AND/OR over three fields. Then someone needs region compared against another field rather than a constant, so you add variables; then thresholds have to be relative, so you add arithmetic; then a rule has to hold across a list, so you add quantifiers, and someone asks for a loop. By then you are maintaining a language with none of the tooling that makes one usable: no debugger, no type checker, and no way for a rule author to test a rule before it meets real traffic. The stop signal is specific – the moment someone asks for a loop or a user-defined function, stop extending your grammar and either adopt an embeddable language with a real sandbox and resource governor, or move to a rules engine. Pushing your own past that point is the textbook case in Over-Engineering: every increment looks small, and the total is a compiler you never planned to own.


Interview Questions

  1. “Interpreter or Specification – how do you choose?” – One question decides it: who authors the rules. If engineers do, Specification wins, because typed predicates composed in code give compile-time field checking and real unit tests with no parser, allowlist, depth cap or migration plan to maintain. If anyone outside the codebase authors them those guarantees are gone whatever you build, and Interpreter rebuilds them as runtime validation over a stored tree. Without user-editable rules it is cost with no benefit.

  2. “How do you stop a malicious or pathological rule from hanging the evaluator?” – Two layers, because they catch different things. At save time the compiler enforces structural limits – a depth cap, a node-count cap, an allowlist of fields and operators – so a bad tree is never stored, and depth must be caught here because recursion makes it unguardable later. At evaluation time the context carries a node budget every node charges against, bounding work per event even for a tree that passed validation, with a fresh budget per rule in its own try/catch so one bad rule cannot silence the rest. The grammar has no loops or function calls, so those limits suffice.

  3. “What if the input is text? Where do precedence and parsing live?” – In a separate layer producing the same tree, so nothing below changes: a lexer, then a recursive-descent or precedence-climbing parser encoding NOT binding tighter than AND binding tighter than OR, then the node classes already written. The honest answer is that I would rather not accept text – it adds a lexer, a precedence table, ambiguity rules and error messages that must satisfy non-programmers, and buys nothing the structured form lacks. Text earns its place only where it is the product requirement, like a formula bar.

  4. “An event field gets renamed. How do you avoid breaking every stored rule?” – Version the rule document and treat the field vocabulary as a published API. A "version": 2 on the stored tree lets the compiler apply a rename map while loading older rules, so an old rule still compiles while new rules reject the old name; write the migrated form back and the map eventually becomes dead code. The failure to design against is silence – a rule naming a field that no longer exists evaluates to false everywhere rather than throwing, indistinguishable from “nothing matched”. That is why KNOWN_FIELDS is checked at compile time, and why a rename migration emits a metric per rule touched.

  5. “Why not just use eval or a scripting engine?” – Two reasons and one real exception. Security: eval runs arbitrary code with the process’s own privileges, so anyone who can save a rule can read your environment, open sockets and reach the filesystem, and host-language interop turns a one-line rule into Runtime.getRuntime().exec. Resources: a script has no bound on time or memory, cannot be safely interrupted mid-run, and cannot be validated without being executed. The exception is genuine – a sandboxed engine with interop and I/O disabled, a hard CPU budget, a wall-clock timeout and somewhere to run where a hang is survivable is the right call when users need expressive power you do not want to grow a grammar for. That is a deliberate decision with a configured sandbox behind it, not reaching for ScriptEngine because it is quicker.


See It in Action

  • Expression Evaluator – this pattern with a parser attached: tokens, precedence, self-evaluating nodes
  • Spreadsheet Engine – a formula cell holds an interpreter tree; the dependency graph picks which to re-run
  • Discount Engine – merchandiser-authored campaign conditions evaluated per cart: this design with money
  • File Search – size > 10MB AND name matches *.log as a filter tree over directory entries