Interpreter

November 27, 20269 minutes

Feature-flag rules hard-coded in if chains mean a deploy for every change. Learn how Interpreter turns a small grammar into classes and a sentence into a tree, and where it stops being a good idea.

Your company runs a feature flag service. It decides who sees the new checkout. The first rule is simple: users in Canada, on the pro plan. Today, that rule is a line of code. So is the dark mode rule. And the next one, and the one after that. Every new rule means a new method, a review, and a deploy. The product team waits, just to change who sees a button. What if a rule were data? Something you build while the program runs, and then ask a question. That’s the Interpreter pattern.

Prefer to watch? The narrated video covers the same lesson (about 8 minutes). The article follows it section by section, with diagrams and a little extra depth.

A rule, a deploy

The flag is “new checkout”, and the rule that switches it on reads country is "CA" and plan is "pro". Written as code it is a method. Then comes darkMode(), then betaBanner(), and each one travels the same road: a method, a review, a deploy.

Sheet music

Think of sheet music. A note knows how it sounds. A rest knows how long to stay quiet. Nobody explains each symbol again.

Some symbols hold other symbols. A repeat sign says: play everything inside me twice. It doesn’t know the notes. It only knows what to do with them.

So a score is a small language, and a bar is a sentence in it. To play it, the musician walks the symbols in order, and each one does its part. In code, each kind of symbol becomes a class. A repeat sign is a class that holds other symbols. And playing the score is interpreting it.

The obvious version

Here’s the obvious version. A flags class, with one method per flag. New checkout is Canada and pro. Dark mode is pro, or Germany. It’s readable, quick to write, and it’s plain Java that the compiler checks.

public final class Flags {
    public boolean newCheckout(User user) {
        return user.country().equals("CA") && user.plan().equals("pro");
    }

    public boolean darkMode(User user) {
        return user.plan().equals("pro") || user.country().equals("DE");
    }
}

For two rules, that’s perfectly fine. The trouble starts when the rules keep coming.

Why it breaks

On Monday, the product team wants Canada or Germany, but not the free plan. On Tuesday, beta users anywhere. Each one is another method.

Worse, the conditions are the same few pieces, shuffled: country, plan, and, or, not. You write them again and again, and every copy can hide a typo ("ca" instead of "CA"). And only developers can change them. Support can’t switch a flag on for one country. They file a ticket, and wait for a release.

These rules are a tiny language, and we write every sentence of it in code. Instead, describe the language once, and keep the sentences as data.

One class per rule: the key idea

Look at what a rule is made of. Some are simple: this field equals this value. Others combine rules: and, or, not. So give every kind of rule its own class. Each class answers one question: does this user match?

A combining rule holds other rules inside it. So a rule written as a sentence becomes a tree. This is the abstract syntax tree.

The example rule as a tree of five objects: an and node at the top, with a country-is-CA test on its left and an or node on its right; the or node holds two plan tests, plan is pro and plan is beta. The example rule as a tree of five objects: an and node at the top, with a country-is-CA test on its left and an or node on its right; the or node holds two plan tests, plan is pro and plan is beta.
The sentence is a tree: five objects, four edges.

The Gang of Four describe it like this (paraphrased): a class for each grammar rule, sentences represented as trees, and an interpreter that walks them.

One class per rule. The sentence is a tree.

Building it

Start with the user. It’s a record with a country and a plan, and a way to look up a field by name.

public record User(String country, String plan) {
    public String get(String field) {
        return switch (field) {
            case "country" -> country;
            case "plan" -> plan;
            default -> null;
        };
    }
}

Now the question. Rule is a sealed interface with one method, matches. Sealed (final in Java 17, JEP 409) restricts which classes may implement it, so these four classes are the whole language.

public sealed interface Rule permits Equals, And, Or, Not {
    boolean matches(User user);
}

The simple rule is a record called Equals. It holds a field name and a value, and it matches when the user’s field is that value.

public record Equals(String field, String value) implements Rule {
    public boolean matches(User user) {
        return value.equals(user.get(field));
    }
}

Now a combiner. And holds a left rule and a right rule. It matches when both do, and it just asks its children.

public record And(Rule left, Rule right) implements Rule {
    public boolean matches(User user) {
        return left.matches(user) && right.matches(user);
    }
}

Or and Not have the same shape. Or needs one of them. Not flips the answer.

public record Or(Rule left, Rule right) implements Rule {
    public boolean matches(User user) {
        return left.matches(user) || right.matches(user);
    }
}

public record Not(Rule inner) implements Rule {
    public boolean matches(User user) {
        return !inner.matches(user);
    }
}
Class diagram: the sealed interface Rule with matches(user), implemented by the records Equals (field, value), And (left, right), Or (left, right) and Not (inner). And and Or each hold two Rule; Not holds one. Class diagram: the sealed interface Rule with matches(user), implemented by the records Equals (field, value), And (left, right), Or (left, right) and Not (inner). And and Or each hold two Rule; Not holds one.
Four small classes, and the interface they share.

Notice what’s missing. No class knows about checkout, or about Canada. Each one only knows how to ask its children.

Walking the tree

Now build a sentence by hand. Country equals Canada, and the plan is pro or beta. That’s five objects, one inside another.

Rule plan = new Or(
        new Equals("plan", "pro"),
        new Equals("plan", "beta"));
Rule newCheckout = new And(new Equals("country", "CA"), plan);

User maya = new User("CA", "pro");
User leo = new User("DE", "pro");

newCheckout.matches(maya);
newCheckout.matches(leo);

As a picture, it’s the tree above. And sits at the top, with the country test on its left, and Or on its right. Or holds the two plan tests.

Ask it about Maya, who is in Canada, on pro. And asks the country first. Canada matches. Then Or asks the plan, and pro matches. So And says yes: true.

Now Leo, who is in Germany. The country test fails, so And answers no at once: false. It never even looks at the plans (the && in And short-circuits). That is interpretation. Each node asks its children, and the answer climbs back up the tree.

Where the tree comes from

So where does the tree come from? Here, we built it by hand. The pattern doesn’t say how to build it (the Gang of Four say it doesn’t address parsing: the tree can come from a table-driven parser, a hand-crafted one, or directly from the client). That isn’t its job.

In practice, a parser reads the text and builds the tree. You can write one yourself, or generate one with a tool like ANTLR, which describes itself as “a powerful parser generator for reading, processing, executing, or translating structured text or binary files”.

Pipeline: the rule text goes into a parser (written by hand or generated), which builds the rule tree; calling matches on the tree gives true or false. Pipeline: the rule text goes into a parser (written by hand or generated), which builds the rule tree; calling matches on the tree gives true or false.
Parsing builds the tree. The pattern interprets it.

The pattern has a few roles. Rule is the abstract expression. Equals is a terminal, a leaf. And, Or and Not are nonterminals, because they hold other rules. The User is the context, the input every node reads. And a client builds the tree, or is handed one.

In the JDK: regular expressions

The JDK has an everyday example. A regular expression is a tiny language, and it’s the example the Gang of Four used to introduce this pattern.

Pattern p = Pattern.compile("pro|beta");
boolean ok = p.matcher("beta").matches();

When you compile a pattern, the JDK builds a structure from it. A comment in the JDK’s own source (java.util.regex.Pattern) says the classes there are “the building components of the object tree that represents a compiled regular expression”, and that each type of object knows how to match its equivalent construct with its match() method. For pro|beta, picture a branch with two literal pieces under it. (That picture is our simplified sketch, not a dump of the real structure.)

That’s an internal detail, not part of the public interface, and the Javadoc for Pattern doesn’t describe it, so don’t rely on it. But it has our shape: a tiny language, turned into a tree, with a match on every node.

The mix-ups

A common mix-up: Interpreter means writing a whole programming language. It doesn’t. It’s for small, simple grammars, like these rules.

It looks like Composite, and it is one: the tree of rules is a composite. Interpreter adds the view that the tree is a sentence in a language.

Sooner or later you want more than matches. Print the rule. Simplify it. Check it. Each one is a new operation on the same classes. You can add them to every class, or use a Visitor, which keeps them outside. In Java 21, a switch over the sealed interface does the same job (pattern matching for switch, JEP 441).

static String show(Rule rule) {
    return switch (rule) {
        case Equals e -> e.field() + " is " + e.value();
        case And a -> "(" + show(a.left()) + " and " + show(a.right()) + ")";
        case Or o -> "(" + show(o.left()) + " or " + show(o.right()) + ")";
        case Not n -> "not " + show(n.inner());
    };
}

The compiler knows the four cases are all of them, so the switch needs no default. Add a fifth class, and every switch that misses it stops compiling.

When not to use it

When should you skip it? When the grammar grows. Dozens of rules means dozens of classes, and the hierarchy gets hard to manage. At that point, use a parser generator, which reads a grammar file and builds the parser for you.

Be careful on hot paths too. Walking a tree of objects for every request is slower than plain code. The Gang of Four note that the fastest interpreters turn the tree into another form first (regular expressions into state machines, for example).

And if the rules never change, an if statement is just fine. Make rules data only when someone has to change them without a deploy.

Decision flowchart. Do the rules change without a deploy? No: plain code, an if is fine. Yes: is the grammar small and simple? No: use a parser generator. Yes: evaluated on a hot path, millions of times? Yes: translate the tree into another form first. No: use Interpreter. Decision flowchart. Do the rules change without a deploy? No: plain code, an if is fine. Yes: is the grammar small and simple? No: use a parser generator. Yes: evaluated on a hot path, millions of times? Yes: translate the tree into another form first. No: use Interpreter.
Small grammar, rules that change: Interpreter.

Recap and checklist

Rules written as if chains mean a deploy for every change. Give every grammar rule a class. A sentence becomes a tree, and evaluating the tree is the interpretation. Parsing is a separate job. Keep the grammar small, and reach for a visitor or a switch when you need more operations.

  • Do the rules change often enough that a deploy per change hurts?
  • Is the grammar small: a handful of rule classes, not dozens?
  • Does each class only ask its children (no class knows about the business meaning)?
  • Is something else responsible for building the tree (a parser, or the client)?
  • Is evaluation off the hot path, or are you ready to translate the tree first?

One class per rule. The sentence is a tree.

Further reading: Gamma et al., Design Patterns (Interpreter); the Javadoc for java.util.regex.Pattern; JEP 409 (sealed classes) and JEP 441 (pattern matching for switch); antlr.org.