A food delivery app runs many offers at once, and its operations team changes them every week. One offer says "$10 off orders of $50 or more in Pune and Mumbai, but not on a first order". If each change waits for an engineer and a release, the offers start late. So the app gives the team a small language. They type cart.total >= 50 AND city IN ("Pune", "Mumbai") AND NOT firstOrder, and the app checks every order at checkout against that rule.
The same shape shows up in alert rules in a monitoring tool, search filters such as status:open label:bug, spreadsheet formulas and access policies. Each one is a small language, and each sentence in it is written once and checked many times.
The Interpreter pattern gives each rule of the language's grammar its own class. A parser reads the text once and builds a tree of those objects, and the tree answers for itself. In this article we build the offer rules twice. The first version splits the text on every check. The second uses the Interpreter pattern. Then we look at what the pattern costs, when a parser generator or a rules engine is the better choice, and how it differs from Composite and Visitor.
All the code is Java. Every snippet without a Sketch label is cut from a project that compiles: the first-version snippets from the text-splitting version, the rest from the finished design. Both programs run, and the outputs shown are what they print.
The rules we are building
The rules must:
- Test five facts about an order:
cart.totalin dollars,cart.items,city,paymentandfirstOrder. - Combine tests with
AND,OR,NOTand brackets.NOTbinds tightest andORloosest, as in Java and SQL. - Answer yes or no for one order.
- Refuse a rule with a mistake when it is saved, and say where the mistake is: an unknown field, a test that does not fit its field, a missing bracket.
- Read each rule once, then check it against many orders on many threads at once.
- Print a rule back as text, for the screen where the team edits it.
This is the figure to draw first in an interview. The rule's precedence is visible in it: the two ANDs gather the tests, and NOT holds only firstOrder. Each box answers for its own part and asks the boxes below it for theirs.
The first version: split the text
The obvious design keeps the rule as a string and reads it whenever an order arrives:
public boolean matches(String rule, Order order) { for (String condition : rule.split(" AND ")) { if (!holds(condition.trim(), order)) { return false; } } return true; } private boolean holds(String condition, Order order) { if (condition.startsWith("NOT ")) { return !holds(condition.substring(4), order); } String[] parts = condition.split(" ", 3); if (parts.length == 1) { return parts[0].equals("firstOrder") && order.firstOrder(); } String operator = parts[1]; String value = parts[2]; switch (parts[0]) { case "cart.total": return compare(order.totalCents(), operator, Long.parseLong(value) * 100); case "cart.items": return compare(order.items(), operator, Long.parseLong(value)); case "city": return value.contains("\"" + order.city() + "\""); case "payment": return value.contains("\"" + order.payment() + "\""); default: return false; } }matches splits the rule on " AND ". Each piece is split again on spaces into a field, an operator and a value, and a switch on the field's name does the test. A piece that starts with NOT is tested and flipped.
This code works for a rule made only of ANDs, written without a typo. For two or three offers that engineers write themselves, it can be enough. The demo checks three rules against a $65 repeat order from Pune and a $25 first order from Delhi:
FLAT10 cart.total >= 50 AND city IN ("Pune", "Mumbai") AND NOT firstOrder
Pune order: true
Delhi order: false
WELCOME50 firstOrder AND cart.totl >= 20
Pune order: false
Delhi order: false
WEEKEND cart.total >= 30 OR firstOrder
Pune order: java.lang.NumberFormatException: For input string: "30 OR firstOrder"
Delhi order: java.lang.NumberFormatException: For input string: "30 OR firstOrder"A typo is never reported. WELCOME50 has cart.totl, so its second piece reaches the default branch on lines 32 and 33, which answers false. The Delhi order is a first order of $25 and should get the offer. Nothing fails, and nothing reports it.
The language has no structure. OR is not a separator, so the WEEKEND rule stays in one piece, and its value becomes "30 OR firstOrder". Long.parseLong throws on every order at checkout. Supporting OR means splitting on OR first and then on AND. Brackets cannot work with split at all, because a split cannot tell an AND inside brackets from one outside them.
The text is read again for every order. With fifty offers, every order splits fifty strings, even though none of them has changed since it was saved.
All three problems come from the same place. The first version never turns the text into anything. It reads the raw string, and it does so at checkout.
The idea
The pattern works like this:
- The language is written down as a grammar: a few rules, each saying what one piece of the language is made of.
- Each grammar rule that does work becomes a class. All the classes implement one interface with one method,
interpret, which takes the facts to check. - A parser reads the text once and builds a tree of those objects. A rule with a mistake never becomes a tree.
- The checkout calls
interpreton the root. Each node answers for its own piece, and asks its children for theirs.
The interface is often called the abstract expression. The leaves that test one fact, here Compare, In and Flag, are terminal expressions. The nodes that hold other expressions, And, Or and Not, are non-terminal expressions. The facts passed in, our Order, are the context. The parser is not part of the pattern itself, but a language typed as text needs one.
Building it, step by step
Step 1: write the grammar down
The whole language fits in eight lines:
or := and ( "OR" and )*and := not ( "AND" not )*not := "NOT" not | primaryprimary := "(" or ")" | testtest := compare | in | flagcompare := field op numberin := field "IN" "(" text ( "," text )* ")"flag := fieldEach line says what one piece is made of. An or is one or more ands joined by OR. An and is one or more nots joined by AND. Because an or is built from ands, every AND is gathered before any OR is, so AND binds tighter. Brackets go back to the top, so anything inside them is gathered first. The order of the lines is the precedence, and no table of operator priorities is needed.
Six of the eight lines become classes: Or, And, Not, Compare, In and Flag. The other two only pass through. primary is either brackets around a whole rule or a test, and test is one of three forms. Neither adds a node of its own to the tree.
A test names a field. The fields are an enum, and each one says what kind of value it holds:
/** The fields a rule may name, and what kind of value each one holds. */public enum Field { CART_TOTAL("cart.total", Kind.MONEY), CART_ITEMS("cart.items", Kind.COUNT), CITY("city", Kind.TEXT), PAYMENT("payment", Kind.TEXT), FIRST_ORDER("firstOrder", Kind.FLAG); /** The kind decides which tests a rule may write on a field. */ public enum Kind { MONEY, COUNT, TEXT, FLAG }The kind decides which tests a rule may write. A money or count field takes a comparison such as >=. A text field takes IN and a list. A flag stands on its own. The facts themselves come in an Order record, with the total in cents.
How is money written in a rule?
In cents, as the code holds it
cart.total >= 5000 matches the code exactly, and no conversion is needed. Nobody on the ops team thinks in cents, though, and a missing zero gives an offer at $5.00.
In dollars, read as a double
49.99 reads naturally. A double cannot hold most amounts with cents exactly, so a rule at the edge of a threshold can give a different answer than its text says.
In dollars in the text, in cents in the treeOur pick
The team writes 50 or 99.50, and the parser turns it into a whole number of cents. More than two digits after the point is refused. The cost is a little parsing code, and toString has to turn cents back into dollars when the rule is printed.
Step 2: a class for each kind of node
The interface has one method:
/** * One piece of an offer rule. Each rule of the grammar is one class, and each * class answers interpret for its own piece and asks its children for theirs. */public interface Expression { boolean interpret(Order order);}And is a record holding two expressions:
/** Both sides must hold. The right side is not asked when the left is false. */public record And(Expression left, Expression right) implements Expression { public And { Objects.requireNonNull(left, "left"); Objects.requireNonNull(right, "right"); } @Override public boolean interpret(Order order) { return left.interpret(order) && right.interpret(order); }Line 17 is the whole rule for AND. The node asks its left side, and asks its right side only when the left said yes. Java's && does that. For the Delhi order, FLAT10's first test fails, so the city test and NOT firstOrder are never asked. Our tests only read fields of a record, so the saving is small today. It grows if a test ever has to call another service, such as a membership check, and it lets the team put the test that fails most often first.
A leaf checks its own field when it is built:
/** A number field compared with a number. Money is held in cents. */public record Compare(Field field, Operator operator, long value) implements Expression { public Compare { Objects.requireNonNull(field, "field"); Objects.requireNonNull(operator, "operator"); if (field.kind() != Field.Kind.MONEY && field.kind() != Field.Kind.COUNT) { throw new IllegalArgumentException(field.ruleName() + " is not a number field"); } if (value < 0) { throw new IllegalArgumentException("value must not be negative: " + value); } } @Override public boolean interpret(Order order) { return operator.test(field.number(order), value); }A Compare on a text field cannot exist, even if code builds one without the parser. Line 24 is the leaf's whole answer: read the number from the order and compare. In and Flag follow the same shape for text and flags. In compares text ignoring case, so an order from "mumbai" still matches "Mumbai". A value may hold spaces inside it, as in "Navi Mumbai", but not at either end, and it cannot hold a ", because the next quote ends it.
Can a tree change after it is built?
Nodes with setters
An edit screen could change a threshold in place, such as setValue(59_900) on one Compare. But the same tree is being read by checkout threads, so a reader could see a rule half-changed, and every reader would need a lock.
Records that never changeOur pick
Every node is a record of final fields, and In copies its list with List.copyOf, so no caller can change it afterwards. Changing an offer means parsing the new text and putting the new tree into the map the checkout reads, a ConcurrentHashMap<String, Expression> keyed by offer code. Final fields make a tree safe to read once a thread can see it, and the map's write makes the new tree visible to other threads. The cost is a whole new tree for every edit, which for a rule of ten tests is about twenty small objects.
Step 3: the parser builds the tree
The parser has one method for each line of the grammar, except flag, which is one arm of test:
private Expression or() { Expression left = and(); while (accept("OR")) { left = new Or(left, and()); } return left; } private Expression and() { Expression left = not(); while (accept("AND")) { left = new And(left, not()); } return left; } private Expression not() { Token start = peek(); if (accept("NOT")) { return new Not(deeper(start, this::not)); } return primary(); } private Expression primary() { Token start = peek(); if (accept("(")) { Expression inside = deeper(start, this::or); if (!accept(")")) { throw unclosed(start); } return inside; } return test(); }Each method calls the methods for the pieces it is made of. or asks and for its left side on line 72, so and gathers every AND before or sees an OR. That is where precedence comes from. The loop bodies on lines 74 and 82 attach each new piece to the tree built so far, so a AND b AND c groups from the left. This style is called recursive descent: the call stack follows the shape of the rule.
How does text become a tree?
A hand-written recursive descent parserOur pick
One method per grammar line except flag, in about 250 lines of code, including the tokenizer. There is no dependency and no build step, and every error message is in our own words.
A parser generator
A tool reads a grammar file and generates the parser. It pays off when the grammar grows or changes often, because the grammar file stays the one place to edit. The cost is a new tool and a build step, and error messages that need extra work to be friendly.
No text at all: a form builds the tree
The edit screen offers dropdowns for field, operator and value, and buttons for AND and OR. A rule with a syntax error cannot be made. The cost is building that screen, and rules become harder to copy, paste, review and compare between versions.
Step 4: refuse a bad rule, and say where
test reads a field name and decides what may follow it:
private Expression test() { Token name = take(Type.WORD, "a field name"); Field field = Field.named(name.text()) .orElseThrow(() -> error(name, "unknown field \"" + name.text() + "\"")); return switch (field.kind()) { case FLAG -> new Flag(field); case TEXT -> in(field); case MONEY, COUNT -> compare(field); }; }Line 110 is the line the first version was missing. An unknown name stops the parse, and the error carries the column where the name starts. Lines 111 to 115 pick the kind of node from the field's kind, so city >= 5 is refused because a text field must be followed by IN.
Where is an unknown field caught?
When the rule is checked
The facts could be a Map<String, Object>, and a test looks its field up when an order arrives. New fields need no code. But a typo then becomes a false or an exception at checkout, which is the first version's problem again.
When the rule is parsed, against a fixed listOur pick
Field lists every name a rule may use. A typo comes back to the person typing the rule, with its column, before any order sees it. The cost is that a new field means a code change: a constant in Field, an arm in each of its three switch expressions, and a component in Order. Field reads values in switch expressions that list every constant and have no default, so a new constant with no reader does not compile.
Amounts are checked here too:
private static long amount(Field field, Token number) { String text = number.text(); int point = text.indexOf('.'); try { if (field.kind() == Field.Kind.COUNT) { if (point >= 0) { throw error(number, field.ruleName() + " is a count, so it takes a whole number"); } return Long.parseLong(text); } if (point < 0) { return Math.multiplyExact(Long.parseLong(text), 100); } String cents = text.substring(point + 1); if (cents.length() > 2) { throw error(number, "an amount has at most two digits after the point"); } long dollars = Long.parseLong(text.substring(0, point)); return Math.addExact(Math.multiplyExact(dollars, 100), Long.parseLong((cents + "0").substring(0, 2))); } catch (NumberFormatException | ArithmeticException e) { throw error(number, "the number " + text + " is too large"); } }Line 164 turns whole dollars into cents. Lines 167 to 171 allow at most two digits after the point and treat 999.5 as 99,950 cents. Math.multiplyExact and Math.addExact refuse an amount too large for a long, instead of letting it wrap round to a negative number.
What does a bad rule look like?
Accept it, and answer false
Saving never fails, and the offer silently never applies. Nobody learns that the rule is wrong.
Throw at the first mistake, with its columnOur pick
parse throws a RuleSyntaxException, and its column() tells the edit screen where to point. The demo prints a caret under that column. A rule either becomes a whole tree or nothing, because the parser returns only after the last token is read. The cost is that a rule with three mistakes takes three saves to fix.
Collect every mistake
All three mistakes come back at once. The parser must then recover after an error and keep reading, which is much harder code to get right for a small gain on rules this short.
The two kinds of failure are kept apart. A RuleSyntaxException is a message for a person. A null rule text, or a Compare built in code on a text field, is a programmer's mistake and throws NullPointerException or IllegalArgumentException.
The parser also sets two limits. A rule is at most 2,000 characters, and it is nested at most 32 levels deep, counting each NOT and each pair of brackets:
private Expression deeper(Token start, Supplier<Expression> part) { depth++; if (depth > MAX_DEPTH) { throw error(start, "a rule is nested at most " + MAX_DEPTH + " levels deep"); } Expression result = part.get(); depth--; return result; }Each level of nesting is a few more calls on the stack in the parser, and for each NOT or bracketed AND or OR, again in interpret. Without this limit, a 2,000-character rule could still nest close to 1,000 brackets deep, which is enough to overflow a small thread stack. The limit also keeps holding if the length limit is ever raised. Tests side by side, such as (firstOrder) AND (firstOrder), do not add up: each bracket counts only while the parser is inside it. A long chain of ANDs is not counted as nesting, but its tree still grows one level deeper per AND. The length limit caps that chain: every test is at least 10 characters, so a rule holds fewer than 200 of them.
Step 5: one tree, many threads
The offer service parses each rule once, when the team saves it, and every checkout thread uses the same tree. Nothing in the tree can change after its constructor runs, and interpret only reads the order it is given. So the threads need no lock.
The parser is different. It keeps its place in the token list in a field, next, so one Parser object must not be shared. parse creates a new one for every call:
public static Expression parse(String text) { Objects.requireNonNull(text, "text"); if (text.codePointCount(0, text.length()) > MAX_LENGTH) { throw new RuleSyntaxException(MAX_LENGTH + 1, "a rule is at most " + MAX_LENGTH + " characters"); } Parser parser = new Parser(tokens(text)); Expression rule = parser.or(); Token last = parser.peek(); if (last.type() != Type.END) { throw error(last, "expected AND, OR or the end of the rule, found " + describe(last)); } return rule; }Line 60 makes parse safe to call from any thread, because no two calls share a Parser. Line 63 refuses anything left over after a complete rule, such as firstOrder firstOrder.
demo/RaceCheck.java has eight threads share three parsed rules. Each thread checks 1,000 orders against them 25 times, and parses the three rules again at the same time:
8 threads shared 3 rules, each parsed once each thread checked 1000 orders against them, 25 times answers that differ from one thread's answers: 0 rules parsed again on every thread that differ from the shared tree: 0
Every answer matched the answer from one thread, and every rule parsed on another thread came out equal to the shared tree. Records compare by their fields, so equals checks the whole tree.
The finished design
Here is FLAT10 checked against the $25 Delhi order, traced through the objects:
The whole project is below. Click any class name in the code to open that class.
package parse; import java.util.ArrayList;import java.util.List;import java.util.Objects;import java.util.Set;import java.util.function.Supplier; import order.Field;import rule.And;import rule.Compare;import rule.Expression;import rule.Flag;import rule.In;import rule.Not;import rule.Operator;import rule.Or; /** * Reads the text of an offer rule and builds its tree, or refuses it. * * or := and ( "OR" and )* * and := not ( "AND" not )* * not := "NOT" not | primary * primary := "(" or ")" | test * test := compare | in | flag * compare := field op number * in := field "IN" "(" text ( "," text )* ")" * flag := field * * Every call to parse gets its own Parser, so parse is safe to call from any thread. */public final class Parser { public static final int MAX_LENGTH = 2_000; public static final int MAX_DEPTH = 32; private enum Type { WORD, KEYWORD, NUMBER, TEXT, SYMBOL, END } private record Token(Type type, String text, int column) { } private static final Set<String> KEYWORDS = Set.of("AND", "OR", "NOT", "IN"); // Two-character symbols come first, so ">=" is never read as ">" then "=". private static final List<String> SYMBOLS = List.of(">=", "<=", "!=", ">", "<", "=", "(", ")", ","); private final List<Token> tokens; private int next = 0; private int depth = 0; private Parser(List<Token> tokens) { this.tokens = tokens; } public static Expression parse(String text) { Objects.requireNonNull(text, "text"); if (text.codePointCount(0, text.length()) > MAX_LENGTH) { throw new RuleSyntaxException(MAX_LENGTH + 1, "a rule is at most " + MAX_LENGTH + " characters"); } Parser parser = new Parser(tokens(text)); Expression rule = parser.or(); Token last = parser.peek(); if (last.type() != Type.END) { throw error(last, "expected AND, OR or the end of the rule, found " + describe(last)); } return rule; } // ------------------------------------------------------------ the grammar private Expression or() { Expression left = and(); while (accept("OR")) { left = new Or(left, and()); } return left; } private Expression and() { Expression left = not(); while (accept("AND")) { left = new And(left, not()); } return left; } private Expression not() { Token start = peek(); if (accept("NOT")) { return new Not(deeper(start, this::not)); } return primary(); } private Expression primary() { Token start = peek(); if (accept("(")) { Expression inside = deeper(start, this::or); if (!accept(")")) { throw unclosed(start); } return inside; } return test(); } private Expression test() { Token name = take(Type.WORD, "a field name"); Field field = Field.named(name.text()) .orElseThrow(() -> error(name, "unknown field \"" + name.text() + "\"")); return switch (field.kind()) { case FLAG -> new Flag(field); case TEXT -> in(field); case MONEY, COUNT -> compare(field); }; } private Expression in(Field field) { Token in = peek(); if (!accept("IN")) { throw error(in, field.ruleName() + " is text, so it takes IN (\"...\"), found " + describe(in)); } expect("(", "an opening bracket"); List<String> values = new ArrayList<>(); do { Token value = take(Type.TEXT, "a value in quotes"); if (In.isBlank(value.text())) { throw error(value, "a value must not be blank"); } if (In.hasSpaceAtEnds(value.text())) { throw error(value, "a value must not start or end with a space"); } values.add(value.text()); } while (accept(",")); expect(")", "a closing bracket"); return new In(field, values); } private Expression compare(Field field) { Token symbol = peek(); Operator operator = symbol.type() == Type.SYMBOL ? Operator.bySymbol(symbol.text()).orElse(null) : null; if (operator == null) { throw error(symbol, field.ruleName() + " is a number, so it takes a comparison such as >=, found " + describe(symbol)); } next++; Token number = take(Type.NUMBER, "a number"); return new Compare(field, operator, amount(field, number)); } // Money is written in dollars, with at most two digits of cents, and kept as cents. private static long amount(Field field, Token number) { String text = number.text(); int point = text.indexOf('.'); try { if (field.kind() == Field.Kind.COUNT) { if (point >= 0) { throw error(number, field.ruleName() + " is a count, so it takes a whole number"); } return Long.parseLong(text); } if (point < 0) { return Math.multiplyExact(Long.parseLong(text), 100); } String cents = text.substring(point + 1); if (cents.length() > 2) { throw error(number, "an amount has at most two digits after the point"); } long dollars = Long.parseLong(text.substring(0, point)); return Math.addExact(Math.multiplyExact(dollars, 100), Long.parseLong((cents + "0").substring(0, 2))); } catch (NumberFormatException | ArithmeticException e) { throw error(number, "the number " + text + " is too large"); } } private Expression deeper(Token start, Supplier<Expression> part) { depth++; if (depth > MAX_DEPTH) { throw error(start, "a rule is nested at most " + MAX_DEPTH + " levels deep"); } Expression result = part.get(); depth--; return result; } // ------------------------------------------------------------ reading tokens private Token peek() { return tokens.get(next); } /** Moves past the next token if it is this keyword or symbol. */ private boolean accept(String text) { Token token = peek(); boolean fixed = token.type() == Type.KEYWORD || token.type() == Type.SYMBOL; if (fixed && token.text().equals(text)) { next++; return true; } return false; } private void expect(String text, String what) { if (!accept(text)) { throw error(peek(), "expected " + what + ", found " + describe(peek())); } } private Token take(Type type, String what) { Token token = peek(); if (token.type() != type) { throw error(token, "expected " + what + ", found " + describe(token)); } next++; return token; } private RuleSyntaxException unclosed(Token open) { Token found = peek(); if (found.type() == Type.END) { return error(open, "this bracket is never closed"); } return error(found, "expected a closing bracket for the one at column " + open.column() + ", found " + describe(found)); } private static RuleSyntaxException error(Token token, String problem) { return new RuleSyntaxException(token.column(), problem); } private static String describe(Token token) { return switch (token.type()) { case END -> "the end of the rule"; case TEXT -> "\"" + token.text() + "\""; default -> token.text(); }; } // ------------------------------------------------------------ splitting the text private static List<Token> tokens(String text) { List<Token> tokens = new ArrayList<>(); int i = 0; while (i < text.length()) { char c = text.charAt(i); int column = columnAt(text, i); if (In.isSpace(c)) { i++; } else if (isDigit(c)) { int end = digitsFrom(text, i); if (end < text.length() && text.charAt(end) == '.') { int after = digitsFrom(text, end + 1); if (after == end + 1) { throw new RuleSyntaxException(columnAt(text, end), "expected a digit after the point"); } end = after; } tokens.add(new Token(Type.NUMBER, text.substring(i, end), column)); i = end; } else if (c == '"') { // A value cannot hold a quote: the next one ends it. int close = text.indexOf('"', i + 1); if (close < 0) { throw new RuleSyntaxException(column, "this quote is never closed"); } tokens.add(new Token(Type.TEXT, text.substring(i + 1, close), column)); i = close + 1; } else if (Character.isLetter(c)) { int end = i; while (end < text.length() && (Character.isLetterOrDigit(text.charAt(end)) || text.charAt(end) == '.')) { end++; } String word = text.substring(i, end); tokens.add(new Token(KEYWORDS.contains(word) ? Type.KEYWORD : Type.WORD, word, column)); i = end; } else { String symbol = symbolAt(text, i); tokens.add(new Token(Type.SYMBOL, symbol, column)); i += symbol.length(); } } tokens.add(new Token(Type.END, "", columnAt(text, text.length()))); return tokens; } private static String symbolAt(String text, int i) { for (String symbol : SYMBOLS) { if (text.startsWith(symbol, i)) { return symbol; } } String character = Character.toString(text.codePointAt(i)); throw new RuleSyntaxException(columnAt(text, i), "unexpected character '" + character + "'"); } // Columns count code points, so a single emoji counts as one. private static int columnAt(String text, int index) { return text.codePointCount(0, index) + 1; } private static boolean isDigit(char c) { return c >= '0' && c <= '9'; } private static int digitsFrom(String text, int i) { int end = i; while (end < text.length() && isDigit(text.charAt(end))) { end++; } return end; }}The demo in demo/Main.java saves three offers, tries five rules with mistakes, and checks five orders:
The ops team saves three offers. Each rule is parsed once:
FLAT10: cart.total >= 50 AND city IN ("Pune", "Mumbai") AND NOT firstOrder
WELCOME50: firstOrder AND cart.total >= 20
UPI20: payment IN ("UPI") AND (cart.items >= 3 OR cart.total > 99.50)
Rules with mistakes are refused when they are saved:
firstOrder AND cart.totl >= 20
^ column 16: unknown field "cart.totl"
cart.total >= 30 OR
^ column 20: expected a field name, found the end of the rule
city >= 5
^ column 6: city is text, so it takes IN ("..."), found >=
cart.items >= 2.5
^ column 15: cart.items is a count, so it takes a whole number
(cart.total >= 50 AND firstOrder
^ column 1: this bracket is never closed
Orders at checkout, and the offers each one gets:
$65.00 2 items, Pune, Card, repeat -> FLAT10
$25.00 1 item, Delhi, UPI, first order -> WELCOME50
$99.50 2 items, Mumbai, UPI, repeat -> FLAT10
$120.00 1 item, mumbai, UPI, repeat -> FLAT10, UPI20
$18.00 4 items, Chennai, UPI, first order -> UPI20The three saved rules print back exactly as they were typed. UPI20 keeps its brackets, because toString in And puts them back around an OR. toString keeps brackets wherever dropping them would change the tree. So for any rule the parser accepted, printing and parsing again gives back the same tree, as long as the printed text stays within 2,000 characters. Printing adds spaces, so a rule typed with none can outgrow the limit. Each refused rule has a caret under the column the parser reported: the typo at column 16, the rule that ends after OR, >= on a text field, half an item, and, at column 1, the bracket that is never closed. The $99.50 order from Mumbai gets FLAT10 but not UPI20, because > 99.50 is strict and it has only 2 items. The order from "mumbai" in lower case still gets FLAT10. The $18 first order misses WELCOME50, which needs $20, and gets UPI20 because it has 4 items.
What it costs
The pattern makes one kind of change cheap and another kind expensive.
A new kind of test is cheap. A test on a new number field, such as delivery distance, is a constant in Field, an arm in each of its three switch expressions, and a component in Order. A new form of test, such as cart.total BETWEEN 20 AND 50, is one new record, a new keyword, a new grammar line and a new branch in the parser. No existing node class changes.
A new question is expensive. The support team wants to know why an order missed an offer. That is a new method, explain, on Expression and in all six classes, and in every class added later. We have already paid this once: toString is a second question, and every node class has its own.
The grammar can grow into a language. Each new grammar rule is a class and a parser method. Arithmetic in rules (cart.total - discount >= 50), functions and variables would each add several. Three other tools fit three different needs. A parser generator helps when the grammar grows or changes often. An existing expression language fits when the team wants a richer language than we want to design. A rules engine fits when the trouble is the number of rules, and which one wins when several apply.
Every check walks the tree. interpret makes one call per node visited, for every order and every offer. For rules of ten tests that is fast. A system with thousands of offers would first narrow the offers to check, for example by city, and might compile rules into faster code instead of walking trees.
When the pattern is too much
If engineers write the rules and they change only with a release, Java is already the rule language:
interface OfferRule { boolean appliesTo(Order order);} final class Flat10 implements OfferRule { private static final Set<String> CITIES = Set.of("Pune", "Mumbai"); @Override public boolean appliesTo(Order order) { return order.totalCents() >= 5_000 && CITIES.contains(order.city()) && !order.firstOrder(); }}The compiler checks every field name, and there is no parser to write. The Interpreter pattern earns its place when people who do not ship code write the rules, and the rules change faster than releases.
Some codebases build the same kind of tree in code instead of text, with and, or and not methods on a rule object: minTotal(5_000).and(inCity("Pune", "Mumbai")). This is the Specification pattern. It is the tree from this article without the parser.
Interpreter, Composite or Visitor?
All three involve a tree of objects, so they are easy to confuse.
| Interpreter | Composite | Visitor | |
|---|---|---|---|
| What it is for | Answering sentences of a small language | Treating one part and a whole group the same way | Adding questions to a fixed set of node kinds |
| Where the tree comes from | A parser reads it from text | Code builds it, such as folders and files | Any existing tree |
| Where the work lives | interpret on each node class | The operation on each node class | One visitor class per question |
| The cheap change | A new kind of node | A new kind of node | A new question |
| Example | Offer rules on this page | Folder sizes on the Composite pattern page | The calculator on the Visitor pattern page |
A short way to say it: Interpreter is a Composite whose classes follow a grammar, usually with a parser in front of it, and when its questions grow, Visitor takes them off the nodes.
In an interview
The pattern appears inside low-level design questions about coupon and offer engines, search filters, alert rules, feature flags with targeting rules, access policies and small calculators. In each one, someone writes rules as text and the system checks them many times.
A good order for presenting it:
- Write the grammar in a few lines, and say that the order of the lines gives the precedence.
- Draw the tree for one example rule, and walk one order through it.
- Write the interface,
Andand one leaf in full. Describe the parser as methods that follow the grammar's lines, and write it only if the interviewer asks.
Common mistakes:
- Parsing the text on every check. Mistakes are then found at checkout, not when the rule is saved.
- Getting precedence by accident. Splitting on
ANDbeforeOR, or building the tree in the order the words arrive, makesa OR b AND cmean the wrong thing. - Answering
falsefor an unknown name. A typo then switches an offer off with no error. - A tree that can change while threads read it. An edit should build a new tree and put it into a map that threads read safely.
- No limits on nesting. A deep enough rule overflows the stack in the parser or in
interpret. - Using the pattern for rules engineers write. A class per rule behind an interface is simpler, and the compiler checks it.
Summary
- Use the Interpreter pattern when people write rules in a small language and the system checks each rule many times.
- Write the grammar first. Each grammar rule that does work becomes a class with
interpret, and the order of the grammar lines gives the precedence. - Parse once, refuse mistakes at save time with their position, and share the finished tree, which never changes, across threads.
- Adding a kind of test is cheap. Adding a question touches every node class, which is where Visitor helps.
- Reach for a parser generator when the grammar keeps changing, an existing expression language when the team needs more, and a rules engine when many rules compete.