Learn

Architecture & pattern guides

Read the idea, build it on a Grid, prove it in a challenge. Short, practical guides — illustrated with RodGrid's own nodes — on system design, design patterns, flow modeling, and how to get the most out of the app.

All articles

Interpreter

Represent each rule of a small language as a class, build each sentence as a tree of those objects, and evaluate it by calling interpret(context) on the root. Parsing the text is a separate job, and large grammars or hot paths call for a parser generator or a dedicated engine.

Contract 4471 wants its own surcharge

A freight company has about 300 customer contracts, and many of them carry their own fuel-surcharge clause. Contract 4471 charges €0.80 per kilogram, with a minimum of €150. Contract 5102 charges €0.05 for every kilometre past the first 500. The billing code handled this with a switch on the contract number inside surcharge(contract, shipment), so every new contract meant a code change, a review and a release.

The sales team asked for something else: type the clause into the contract record, as max(150, weight * 0.8), and let billing work it out for each shipment. That turns the clauses into sentences of a small language, with numbers, shipment fields such as weight and distance, the operators +, - and *, and a max function. Billing now needs a way to represent a sentence of that language and evaluate it.

A class for each rule

Interpreter represents the grammar of a simple language as classes. Each rule becomes an expression class, and every expression class implements the same operation, interpret(context). The classes come in two kinds:

  • Terminal expressions are the atoms of the language. Number holds a constant and returns it. Variable holds a name such as weight and looks its value up in the context.
  • Non-terminal expressions are the rules built from other expressions. Add, Subtract, Multiply and Max each hold two sub-expressions; their interpret calls interpret(context) on each sub-expression and combines the two results.

A sentence is then a tree of these objects. max(150, weight * 0.8) is a Max whose two operands are Number(150) and a Multiply, and the Multiply holds Variable("weight") and Number(0.8). The context carries what the sentence is evaluated against, here the shipment's fields. The client calls interpret(context) on the root, and each non-terminal delegates to its sub-expressions. No separate object walks the tree: evaluating a sentence is the expression objects calling one another.

One clause as a tree

The client calls interpret(ctx) on the root, Max. Each non-terminal passes the same context to its operands, and only the Variable reads from it.

For a 1,200 kg pallet, Variable returns 1200, Multiply returns 960, and Max compares 150 with 960 and returns 960. For a 90 kg parcel the same tree returns 150, because 72 is under the minimum. The tree was built once, when the clause was saved; only the context changes from one shipment to the next.

That split is easy to undo by accident. If a Variable is built as new Variable("weight", shipment.weight), the tree describes one shipment and has to be rebuilt for every invoice. If billing instead caches one tree per contract and sets the weight on it before each invoice, two invoices computed at once overwrite each other's weight, because they share the same objects. Keep expression objects unchanged after they are built, and pass everything that varies in the context.

Where the tree comes from

The pattern starts from a tree that already exists. Turning the text max(150, weight * 0.8) into those objects is parsing, and Interpreter does not cover it. Something else builds the tree. It can be a parser, written by hand for a grammar this size or generated by a tool such as ANTLR for a larger one. Or there can be no text at all: a form where sales pick minimum of, fill in two boxes, and save the resulting tree as JSON. Either way, the builder is where bad input such as max(150, weight * gets refused, when the clause is saved rather than when an invoice is due.

New rules are cheap; new operations are not

Contract 6230 needs a cap: min(weight * 0.8, 400). That is one new class, Min, with two operands and an interpret that returns the smaller result. No other expression class changes; only whatever builds the trees, the parser or the form, has to learn min. With a grammar that grows slowly, this is what makes the pattern pleasant to live with.

Then finance asks for more things to do with each clause: print it in words on the invoice, and list the fields it uses so the contract screen can warn when a shipment lacks one. Each request is a new method on every expression class, describe() and fields() next to interpret(). With seven classes that is manageable. The tree shape itself, where a single expression and an expression made of others answer through one interface, comes from Composite. If new operations keep arriving while the expression classes stay put, each can move into its own object; Visitor shows how, and what a new expression class then costs.

Drawing the tree in the Challenge

The Interpreter Pattern Challenge asks for an abstract Expression interface with an interpret operation, terminal expressions, non-terminal expressions that compose sub-expressions, a Context, and a client that builds the tree and triggers interpret, in at most ten nodes. The surcharge clause fits in seven: an Expression interface, Number and Variable as terminals, Max and Multiply as non-terminals, a Context and a Client. Point the non-terminals' operand edges at the Expression interface, not at particular classes, since an operand can be any expression. In a drawing that tells the story, the terminals have no operand edges, the Client has a single edge to the root, and the Context is read only by Variable.

When the grammar outgrows the classes

The pattern is a good fit for small, stable grammars. Every rule is a class, so a language with conditionals, dates and string functions becomes dozens of classes, plus a parser that has to handle operator precedence and point its error messages at a column, and the expression-tree code turns into its own maintenance burden. For anything that complex, a parser generator can take over the parsing, and an existing expression language or rules engine the evaluation, instead of hand-rolled expression classes. Stable matters too: the saved clauses have to keep evaluating to the same amounts after every change to the grammar.

Speed is the other limit. Evaluating a tree typically costs a method call per node, every time. Once per invoice, nobody will notice. In a path that evaluates a formula millions of times, such as pricing a whole catalogue on every request, that overhead can show, and efficient engines usually translate the tree into another form before running it: bytecode, generated code, or a state machine, as many regular-expression engines do. Before writing that yourself, look for an existing expression language or rules engine that already does it. And since users write these sentences, cap their size and depth when building the trees: a clause nested thousands of levels deep can exhaust the stack of a recursive interpret.

Practice this