Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 57 ยท Behavioral Patterns

Interpreter Pattern in Depth

Learn the Interpreter design pattern step by step: define a grammar, build terminal and non-terminal expression classes, parse text into a tree and evaluate it.

Some problems are best solved by giving users a tiny language. A shop owner writes price > 100 and country = "DE" to decide who gets free shipping. A support tool lets agents filter tickets with status:open AND priority:high. A spreadsheet cell holds =A1 + B1 * 2. In every case you receive a sentence as text and must work out what it means.

The Interpreter pattern solves this by modeling the grammar of the language as classes. Each grammar rule becomes a class with an interpret (or evaluate) method, and a sentence becomes a tree of those objects. Running the tree gives the answer. The lesson on Visitor and Other Patterns introduced the idea briefly; here you will go through the whole path from grammar to parsed, evaluated text.

Grammar, terminals and non-terminals

A grammar lists the rules that say which sentences are valid. A common notation is BNF. Here is a small grammar for arithmetic with variables:

TEXT
expression := term (("+" | "-") term)*
term       := factor (("*" | "/") factor)*
factor     := NUMBER | IDENTIFIER | "(" expression ")"

Read it as: an expression is a term, followed by zero or more "plus or minus another term". The nesting of the rules (expression uses term, term uses factor) is what gives * higher precedence than +, with no extra code.

In the Interpreter pattern the symbols divide into two groups:

  • Terminal expressions are the leaves. They are not defined in terms of other expressions: a number, a variable.
  • Non-terminal expressions are built from other expressions: an addition has a left and a right expression, a negation has one.
classDiagram
    class Expression {
        <<interface>>
        +evaluate(context) number
    }
    class Num
    class Variable
    class BinaryOp
    Expression <|.. Num
    Expression <|.. Variable
    Expression <|.. BinaryOp
    BinaryOp o-- Expression : left
    BinaryOp o-- Expression : right

Terminals (Num, Variable) have no children; the non-terminal (BinaryOp) holds two expressions and combines their results.

The context is whatever the sentence needs from outside, such as the values of variables. It is passed to evaluate, so the same tree can run against many inputs.

Step 1: the expression classes

The tree for price * quantity + 5 looks like an addition whose left child is a multiplication. Build it by hand first to see that the pattern itself is just objects and recursion.

JS Building and evaluating a tree by hand

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Evaluation is plain recursion: evaluate on the root calls evaluate on its children, and the leaves return values. Nothing in the pattern says how the tree is built; that is the next step.

Step 2: a parser that builds the tree

The pattern does not include parsing, but you need one unless you build every tree in code. For a small grammar a recursive-descent parser is the easiest approach: write one function per grammar rule, and each function calls the rules it is built from.

JS From text to tree to answer

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Look at 1 + 2 * 3: the printed tree is (1 + (2 * 3)) because term is called from inside expression, so multiplication binds tighter. The grammar's structure produced the precedence, and the error cases come from the parser, not from the expression classes. Bad input never reaches evaluate.

Step 3: a business-rule language

The same recipe works for conditions. Add comparison and logical nodes, and a user can express a rule as text that is stored in a database or config file and evaluated against thousands of records. Because the rule is a tree of objects, it can also be printed back, validated before saving, or optimized.

JS A rule language for discounts

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Here the nodes are small factories and closures instead of classes. That is the same pattern: each node still knows how to evaluate itself from its children. JavaScript lets you write nodes either way. In Java or C#, you would use one class per node type, implementing a common Expression interface.

Adding a new operation

Adding a new node type is easy: write one more class (Not, Between, Power) and teach the parser about it. Existing classes do not change. Adding a new operation over the whole tree is harder, because every node class needs a new method. If you need many operations (evaluate, print, simplify, type-check, compile), switch to a design where the tree holds only data and the operations live outside in a Visitor. Real compilers do exactly that: the tree is built once and every pass is a visitor.

When not to use Interpreter

  • Large or changing grammars. One class per rule explodes in size, and performance suffers from many small objects and virtual calls. Use a parser generator (ANTLR, PEG libraries) or a real embedded language.
  • You do not need a language. If users only pick from three options, a dropdown or a Strategy per option is simpler and safer.
  • Security. Never eval user text as a shortcut. An interpreter you wrote evaluates only what your grammar allows, which is its main safety advantage. Still limit input size and recursion depth, and keep side effects out of the context.
  • Speed matters. A tree-walking interpreter is slow for hot loops. Compile the tree to a function or bytecode if you evaluate millions of times.

Good uses are small, stable languages: filter and search queries, pricing and validation rules, routing expressions, feature-flag conditions, formula fields and configuration with logic. Regular expressions are a famous everyday example: the engine parses a pattern into a tree of nodes and matches input against it.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In the Interpreter pattern, what is a terminal expression?

    Terminal expressions are the leaves. Non-terminals, like addition, are built from other expressions.
  2. 2. What is the context passed to evaluate used for?

    The tree describes the rule; the context supplies the data. That separation lets you evaluate the same rule for many records.
  3. 3. Why does a recursive-descent parser give * higher precedence than + in the example?

    Precedence comes from the nesting of grammar rules: terms are built inside expressions, so they bind tighter.
  4. 4. Which situation makes Interpreter a poor choice?

    One class per rule becomes unmanageable for big grammars. A parser generator or existing language is better.
  5. 5. You need five different operations over the same expression tree (evaluate, print, simplify, type-check, compile). What is the better design?

    Adding operations to every node class does not scale. Visitor puts each operation in one place.

Summary

  • Interpreter represents a grammar as classes: terminals are leaves, non-terminals combine child expressions.
  • A sentence becomes a tree; evaluate(context) walks it recursively.
  • The pattern does not parse text; use a hand-written recursive-descent parser for small grammars, where precedence comes from the rule nesting.
  • It suits small, stable languages: filters, pricing rules, validation and formulas.
  • New node types are easy; new operations over the tree call for Visitor.
  • Avoid it for big grammars, hot loops and anything where eval is tempting.

Next lesson: Null Object Pattern.