# InterpreterFeature-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.

{{< lesson-video youtube="z6_9fuy1DF4" title="Interpreter" >}}

## 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.

```java
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**.

```mermaid {alt="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." caption="The sentence is a tree: five objects, four edges."}
flowchart TD
  A["and"] --> E["country is CA"]
  A --> O["or"]
  O --> P1["plan is pro"]
  O --> P2["plan is beta"]
  class A,O c5
  class E,P1,P2 c1
```

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.

```java
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.

```java
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.

```java
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.

```java
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.

```java
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);
    }
}
```

```mermaid {alt="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." caption="Four small classes, and the interface they share."}
classDiagram
  class Rule {
    <<sealed interface>>
    +matches(user) boolean
  }
  class Equals {
    <<record>>
    +field
    +value
  }
  class And {
    <<record>>
    +left
    +right
  }
  class Or {
    <<record>>
    +left
    +right
  }
  class Not {
    <<record>>
    +inner
  }
  Rule <|.. Equals
  Rule <|.. And
  Rule <|.. Or
  Rule <|.. Not
  And --> Rule : holds two
  Or --> Rule : holds two
  Not --> Rule : holds one
```

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.

```java
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".

```mermaid {alt="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." caption="Parsing builds the tree. The pattern interprets it."}
flowchart TD
  T["rule text"] --> P["parser"]
  P --> R["rule tree"]
  R --> M["matches"]
  M --> V["true / false"]
  class T warn
  class P muted
  class R c5
  class M c6
  class V good
```

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.

```java
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](/patterns/composite-pattern/), 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](/patterns/visitor-pattern/), which keeps them outside. In Java 21, a switch over the
sealed interface does the same job (pattern matching for `switch`, JEP 441).

```java
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.

```mermaid {alt="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." caption="Small grammar, rules that change: Interpreter."}
flowchart TD
  Q1{"Do the rules change<br/>without a deploy?"} -- no --> N1["Plain code: an if is fine"]
  Q1 -- yes --> Q2{"Is the grammar<br/>small and simple?"}
  Q2 -- no --> N2["Use a parser generator"]
  Q2 -- yes --> Q3{"Evaluated on a hot path,<br/>millions of times?"}
  Q3 -- yes --> N3["Translate the tree into<br/>another form first"]
  Q3 -- no --> Y["Use Interpreter"]
  class N1,N2,N3 bad
  class Y good
```

## 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.
