# Interpreter: A Little Language for Rules

When business rules change every week and live in code as one if per rule, every new rule waits for a developer; the Interpreter pattern turns each rule into a tree of small pieces (a check, an and, an or, a not) that each answer one question, so a new rule is data, not code.

Freelancer · OOP · Updated November 17, 2026

By Gregor Dzierzon

## After this lesson you can

- Build a rule as a tree of small pieces that each answer one question, joined by and, or and not
- Spot the smells that point to Interpreter: rules that change often, hard-coded as one if per rule
- Choose between plain code, a rule tree and a parser library for rules users write, and say why

## Key takeaways

- The smell: one if per rule, in code, for rules that change every week and belong to someone who isn't a developer.
- The cause: the rules are really data, but they're stored as code, so only a developer can add one.
- The fix: a few small pieces (checks, and, or, not), each answering "does this order qualify?", snapped together into a tree.
- The same tree can be built from functions; when users type a whole language as text, a parser library builds the tree.

**Before this:** *Composite: Boxes Inside Boxes* (a tree where a box and a pallet answer the same question), interfaces, and passing a function as a value.

Trailhead Outfitters sells hiking gear online, and its marketing team runs a new coupon almost every week. Today every coupon is a ticket for a developer, who writes an `if`, tests it and waits for the next release. Marketing wants an admin screen where they build rules themselves: pick "total over", type 50, pick "and", pick "has a", choose "shoe", in shapes nobody has thought of yet. By the end of this lesson you'll have built the tiny language that screen needs, and met the pattern behind it, *Interpreter*.

## The symptom: a new if for every coupon

The store sells four products: hiking boots ($120, a shoe), a rain jacket ($80), a water bottle ($15) and trail socks ($12). Here are this week's coupons and three customers' orders:

```csharp
Product boots = new Product("Hiking boots", 120, "shoe");
Product jacket = new Product("Rain jacket", 80, "jacket");
Product bottle = new Product("Water bottle", 15, "bottle");
Product socks = new Product("Trail socks", 12, "socks");
List<Order> orders = new List<Order>
{
    new Order("Maya", new List<Product> { boots, socks }),
    new Order("Sam", new List<Product> { jacket }),
    new Order("Leo", new List<Product> { bottle, socks }),
};

// Marketing wrote BOOTS20 on Monday: "has a shoe and total over $100".
List<string> coupons = new List<string> { "TRAIL10", "BOTTLE", "BOOTS20" };
foreach (Order order in orders)
{
    List<string> codes = coupons.Where(code => Qualifies(code, order)).ToList();
    Console.WriteLine($"{order.Customer} (${order.Total()}): {(codes.Count > 0 ? string.Join(", ", codes) : "none")}");
}

bool Qualifies(string code, Order order)
{
    if (code == "TRAIL10") { return order.Total() > 50 && (order.Has("shoe") || order.Has("jacket")); }
    if (code == "BOTTLE") { return order.Has("jacket") && !order.Has("bottle"); }
    return false;
}

record Product(string Name, int Price, string Kind);

record Order(string Customer, List<Product> Products)
{
    public int Total() => Products.Sum(product => product.Price);
    public bool Has(string kind) => Products.Any(product => product.Kind == kind);
}
```

```text
Maya ($132): TRAIL10
Sam ($80): TRAIL10, BOTTLE
Leo ($27): none
```

```java
record Product(String name, int price, String kind) {}

record Order(String customer, List<Product> products) {
    int total() { return products.stream().mapToInt(Product::price).sum(); }
    boolean has(String kind) { return products.stream().anyMatch(product -> product.kind().equals(kind)); }
}

boolean qualifies(String code, Order order) {
    if (code.equals("TRAIL10")) { return order.total() > 50 && (order.has("shoe") || order.has("jacket")); }
    if (code.equals("BOTTLE")) { return order.has("jacket") && !order.has("bottle"); }
    return false;
}

void main() {
    Product boots = new Product("Hiking boots", 120, "shoe");
    Product jacket = new Product("Rain jacket", 80, "jacket");
    Product bottle = new Product("Water bottle", 15, "bottle");
    Product socks = new Product("Trail socks", 12, "socks");
    List<Order> orders = List.of(
        new Order("Maya", List.of(boots, socks)),
        new Order("Sam", List.of(jacket)),
        new Order("Leo", List.of(bottle, socks)));

    // Marketing wrote BOOTS20 on Monday: "has a shoe and total over $100".
    List<String> coupons = List.of("TRAIL10", "BOTTLE", "BOOTS20");
    for (Order order : orders) {
        List<String> codes = coupons.stream().filter(code -> qualifies(code, order)).toList();
        IO.println(order.customer() + " ($" + order.total() + "): " + (codes.isEmpty() ? "none" : String.join(", ", codes)));
    }
}
```

```text
Maya ($132): TRAIL10
Sam ($80): TRAIL10, BOTTLE
Leo ($27): none
```

```python
class Product:
    def __init__(self, name, price, kind):
        self.name = name
        self.price = price
        self.kind = kind


class Order:
    def __init__(self, customer, products):
        self.customer = customer
        self.products = products

    def total(self):
        return sum(product.price for product in self.products)

    def has(self, kind):
        return any(product.kind == kind for product in self.products)


def qualifies(code, order):
    if code == "TRAIL10":
        return order.total() > 50 and (order.has("shoe") or order.has("jacket"))
    if code == "BOTTLE":
        return order.has("jacket") and not order.has("bottle")
    return False


boots = Product("Hiking boots", 120, "shoe")
jacket = Product("Rain jacket", 80, "jacket")
bottle = Product("Water bottle", 15, "bottle")
socks = Product("Trail socks", 12, "socks")
orders = [Order("Maya", [boots, socks]), Order("Sam", [jacket]), Order("Leo", [bottle, socks])]

# Marketing wrote BOOTS20 on Monday: "has a shoe and total over $100".
coupons = ["TRAIL10", "BOTTLE", "BOOTS20"]
for order in orders:
    codes = [code for code in coupons if qualifies(code, order)]
    print(f"{order.customer} (${order.total()}): {', '.join(codes) or 'none'}")
```

```text
Maya ($132): TRAIL10
Sam ($80): TRAIL10, BOTTLE
Leo ($27): none
```

```javascript
class Product {
  constructor(name, price, kind) {
    this.name = name;
    this.price = price;
    this.kind = kind;
  }
}

class Order {
  constructor(customer, products) {
    this.customer = customer;
    this.products = products;
  }

  total() { return this.products.reduce((sum, product) => sum + product.price, 0); }
  has(kind) { return this.products.some((product) => product.kind === kind); }
}

function qualifies(code, order) {
  if (code === "TRAIL10") { return order.total() > 50 && (order.has("shoe") || order.has("jacket")); }
  if (code === "BOTTLE") { return order.has("jacket") && !order.has("bottle"); }
  return false;
}

const boots = new Product("Hiking boots", 120, "shoe");
const jacket = new Product("Rain jacket", 80, "jacket");
const bottle = new Product("Water bottle", 15, "bottle");
const socks = new Product("Trail socks", 12, "socks");
const orders = [new Order("Maya", [boots, socks]), new Order("Sam", [jacket]), new Order("Leo", [bottle, socks])];

// Marketing wrote BOOTS20 on Monday: "has a shoe and total over $100".
const coupons = ["TRAIL10", "BOTTLE", "BOOTS20"];
for (const order of orders) {
  const codes = coupons.filter((code) => qualifies(code, order));
  console.log(`${order.customer} ($${order.total()}): ${codes.join(", ") || "none"}`);
}
```

```text
Maya ($132): TRAIL10
Sam ($80): TRAIL10, BOTTLE
Leo ($27): none
```

```typescript
class Product {
  name: string;
  price: number;
  kind: string;

  constructor(name: string, price: number, kind: string) {
    this.name = name;
    this.price = price;
    this.kind = kind;
  }
}

class Order {
  customer: string;
  products: Product[];

  constructor(customer: string, products: Product[]) {
    this.customer = customer;
    this.products = products;
  }

  total(): number { return this.products.reduce((sum, product) => sum + product.price, 0); }
  has(kind: string): boolean { return this.products.some((product) => product.kind === kind); }
}

function qualifies(code: string, order: Order): boolean {
  if (code === "TRAIL10") { return order.total() > 50 && (order.has("shoe") || order.has("jacket")); }
  if (code === "BOTTLE") { return order.has("jacket") && !order.has("bottle"); }
  return false;
}

const boots = new Product("Hiking boots", 120, "shoe");
const jacket = new Product("Rain jacket", 80, "jacket");
const bottle = new Product("Water bottle", 15, "bottle");
const socks = new Product("Trail socks", 12, "socks");
const orders = [new Order("Maya", [boots, socks]), new Order("Sam", [jacket]), new Order("Leo", [bottle, socks])];

// Marketing wrote BOOTS20 on Monday: "has a shoe and total over $100".
const coupons = ["TRAIL10", "BOTTLE", "BOOTS20"];
for (const order of orders) {
  const codes = coupons.filter((code) => qualifies(code, order));
  console.log(`${order.customer} ($${order.total()}): ${codes.join(", ") || "none"}`);
}
```

```text
Maya ($132): TRAIL10
Sam ($80): TRAIL10, BOTTLE
Leo ($27): none
```

Maya's order has a shoe and costs $132, so BOOTS20 ("has a shoe and total over $100") should apply. It doesn't. Marketing added it to the list on Monday, but `qualifies` has never heard of it, so it quietly says no. Making it work means a developer adding a third `if`. Next week, a fourth.

Read it as a doctor would:

- **The symptom:** one `if` per rule, in code, growing every week, for rules a developer doesn't own.
- **The cause:** the rules are really data. They change often, and someone else writes them. But they live in code, so only a developer can add one, and every mix of "and", "or" and "not" is written by hand.
- **The cure:** coming up, once we've tried the obvious fixes.

## What would you try?

**One more `if` per coupon.** It makes BOOTS20 work today. But every coupon still waits for a developer and a release, and marketing's list and the code drift apart, as they did on Monday.

**A table with a column for each check:** a minimum total, "needs a shoe", "needs a jacket". Marketing can fill in rows themselves, but a row only says "this and this and this". "A shoe *or* a jacket" and "not a bottle" each need a new column, and the table grows rules of its own.

**Run marketing's text as code,** with `eval` in Python or JavaScript. It runs anything anyone types, including code that empties the database, and a typo shows marketing a Python error.

What we want is a handful of pieces that snap together in any shape: a few **checks** ("total over", "has a") and a few **joins** ("and", "or", "not"). Then code that can answer "does this order qualify?" for any shape marketing builds.

## The everyday version: a recipe card's shorthand

A kitchen already has a little language. A recipe card says "2 c. flour, 1 tsp. salt, bake 350°, 30 min", and every cook can read it, even a card written tomorrow by someone they've never met. Each piece of shorthand means one thing ("c." is a cup, "350°" is the oven's dial), and the pieces combine into any recipe. A new recipe doesn't need a new cook, only a new card.

![A recipe card on a kitchen counter written in cooks' shorthand, "2 c. flour", "1 tsp. salt" and "bake 350°, 30 min", with a measuring cup, a teaspoon and an oven dial beside it, each one showing what one piece of the shorthand means](https://fsdtrainingmedia.blob.core.windows.net/public/images/2026/11/641d8f9f6ad94bae873e74f159dc0a12.webp)

## The fix: a rule is a tree of small pieces

**The fix in one sentence:** each piece of a rule becomes a small object that answers "does this order qualify?"; a check answers by looking at the order, and a join answers by asking the pieces it holds.

Here is TRAIL10, "total over $50 and (has a shoe or has a jacket)", as a tree. To answer for Maya's order, the "and" at the top asks its two pieces. "Total over $50" looks at the total: yes. The "or" asks its own two pieces: "has a shoe" says yes, "has a jacket" says no, so the "or" says yes. Both of the "and"'s pieces said yes, so TRAIL10 applies. No piece knows anything about the others; each answers only its own question.

![TRAIL10 as a tree of five small pieces: an "and" holding "total over $50" and an "or", which holds "has a shoe" and "has a jacket". Beside each piece, its answer for Maya's $132 order of hiking boots and trail socks: yes everywhere except "has a jacket", so the coupon applies](https://fsdtrainingmedia.blob.core.windows.net/public/images/2026/11/f1ad1a62cf40469eb2081d2f21256ac1.webp)

Drawn as roles, there are only two kinds of piece, and the fence goes around what marketing changes:

![Interpreter's roles: the coupon check asks a piece of a rule whether an order qualifies. In a dashed fence of what changes, two kinds of piece: a check (total over, has a), which looks at the order, and a join (and, or, not), which holds 1 or 2 pieces and asks them](https://fsdtrainingmedia.blob.core.windows.net/public/images/2026/11/b2ea98426079447f957b88395c7fda16.webp)

Here is the same program with the rules as trees:

```csharp
Product boots = new Product("Hiking boots", 120, "shoe");
Product jacket = new Product("Rain jacket", 80, "jacket");
Product bottle = new Product("Water bottle", 15, "bottle");
Product socks = new Product("Trail socks", 12, "socks");
List<Order> orders = new List<Order>
{
    new Order("Maya", new List<Product> { boots, socks }),
    new Order("Sam", new List<Product> { jacket }),
    new Order("Leo", new List<Product> { bottle, socks }),
};

// Each rule is a tree of small pieces. The admin screen builds these from marketing's choices.
Dictionary<string, IRule> rules = new Dictionary<string, IRule>
{
    ["TRAIL10"] = new And(new TotalOver(50), new Or(new Has("shoe"), new Has("jacket"))),
    ["BOTTLE"] = new And(new Has("jacket"), new Not(new Has("bottle"))),
    ["BOOTS20"] = new And(new Has("shoe"), new TotalOver(100)),
};
foreach (Order order in orders)
{
    List<string> codes = rules.Where(rule => rule.Value.Qualifies(order)).Select(rule => rule.Key).ToList();
    Console.WriteLine($"{order.Customer} (${order.Total()}): {(codes.Count > 0 ? string.Join(", ", codes) : "none")}");
}

// Every piece of a rule answers one question.
interface IRule { bool Qualifies(Order order); }

// The leaves: each checks one thing about the order.
class TotalOver(int amount) : IRule { public bool Qualifies(Order order) => order.Total() > amount; }
class Has(string kind) : IRule { public bool Qualifies(Order order) => order.Has(kind); }

// The joins: each holds other pieces and asks them.
class And(IRule left, IRule right) : IRule { public bool Qualifies(Order order) => left.Qualifies(order) && right.Qualifies(order); }
class Or(IRule left, IRule right) : IRule { public bool Qualifies(Order order) => left.Qualifies(order) || right.Qualifies(order); }
class Not(IRule rule) : IRule { public bool Qualifies(Order order) => !rule.Qualifies(order); }

record Product(string Name, int Price, string Kind);

record Order(string Customer, List<Product> Products)
{
    public int Total() => Products.Sum(product => product.Price);
    public bool Has(string kind) => Products.Any(product => product.Kind == kind);
}
```

```text
Maya ($132): TRAIL10, BOOTS20
Sam ($80): TRAIL10, BOTTLE
Leo ($27): none
```

```java
record Product(String name, int price, String kind) {}

record Order(String customer, List<Product> products) {
    int total() { return products.stream().mapToInt(Product::price).sum(); }
    boolean has(String kind) { return products.stream().anyMatch(product -> product.kind().equals(kind)); }
}

// Every piece of a rule answers one question.
interface Rule { boolean qualifies(Order order); }

// The leaves: each checks one thing about the order.
record TotalOver(int amount) implements Rule { public boolean qualifies(Order order) { return order.total() > amount; } }
record Has(String kind) implements Rule { public boolean qualifies(Order order) { return order.has(kind); } }

// The joins: each holds other pieces and asks them.
record And(Rule left, Rule right) implements Rule { public boolean qualifies(Order order) { return left.qualifies(order) && right.qualifies(order); } }
record Or(Rule left, Rule right) implements Rule { public boolean qualifies(Order order) { return left.qualifies(order) || right.qualifies(order); } }
record Not(Rule rule) implements Rule { public boolean qualifies(Order order) { return !rule.qualifies(order); } }

void main() {
    Product boots = new Product("Hiking boots", 120, "shoe");
    Product jacket = new Product("Rain jacket", 80, "jacket");
    Product bottle = new Product("Water bottle", 15, "bottle");
    Product socks = new Product("Trail socks", 12, "socks");
    List<Order> orders = List.of(
        new Order("Maya", List.of(boots, socks)),
        new Order("Sam", List.of(jacket)),
        new Order("Leo", List.of(bottle, socks)));

    // Each rule is a tree of small pieces. The admin screen builds these from marketing's choices.
    Map<String, Rule> rules = new LinkedHashMap<>();
    rules.put("TRAIL10", new And(new TotalOver(50), new Or(new Has("shoe"), new Has("jacket"))));
    rules.put("BOTTLE", new And(new Has("jacket"), new Not(new Has("bottle"))));
    rules.put("BOOTS20", new And(new Has("shoe"), new TotalOver(100)));
    for (Order order : orders) {
        List<String> codes = rules.keySet().stream().filter(code -> rules.get(code).qualifies(order)).toList();
        IO.println(order.customer() + " ($" + order.total() + "): " + (codes.isEmpty() ? "none" : String.join(", ", codes)));
    }
}
```

```text
Maya ($132): TRAIL10, BOOTS20
Sam ($80): TRAIL10, BOTTLE
Leo ($27): none
```

```python
class Product:
    def __init__(self, name, price, kind):
        self.name = name
        self.price = price
        self.kind = kind


class Order:
    def __init__(self, customer, products):
        self.customer = customer
        self.products = products

    def total(self):
        return sum(product.price for product in self.products)

    def has(self, kind):
        return any(product.kind == kind for product in self.products)


# Every piece of a rule answers one question: qualifies(order).
# The leaves: each checks one thing about the order.
class TotalOver:
    def __init__(self, amount):
        self.amount = amount

    def qualifies(self, order):
        return order.total() > self.amount


class Has:
    def __init__(self, kind):
        self.kind = kind

    def qualifies(self, order):
        return order.has(self.kind)


# The joins: each holds other pieces and asks them.
class And:
    def __init__(self, left, right):
        self.left = left
        self.right = right

    def qualifies(self, order):
        return self.left.qualifies(order) and self.right.qualifies(order)


class Or:
    def __init__(self, left, right):
        self.left = left
        self.right = right

    def qualifies(self, order):
        return self.left.qualifies(order) or self.right.qualifies(order)


class Not:
    def __init__(self, rule):
        self.rule = rule

    def qualifies(self, order):
        return not self.rule.qualifies(order)


boots = Product("Hiking boots", 120, "shoe")
jacket = Product("Rain jacket", 80, "jacket")
bottle = Product("Water bottle", 15, "bottle")
socks = Product("Trail socks", 12, "socks")
orders = [Order("Maya", [boots, socks]), Order("Sam", [jacket]), Order("Leo", [bottle, socks])]

# Each rule is a tree of small pieces. The admin screen builds these from marketing's choices.
rules = {
    "TRAIL10": And(TotalOver(50), Or(Has("shoe"), Has("jacket"))),
    "BOTTLE": And(Has("jacket"), Not(Has("bottle"))),
    "BOOTS20": And(Has("shoe"), TotalOver(100)),
}
for order in orders:
    codes = [code for code, rule in rules.items() if rule.qualifies(order)]
    print(f"{order.customer} (${order.total()}): {', '.join(codes) or 'none'}")
```

```text
Maya ($132): TRAIL10, BOOTS20
Sam ($80): TRAIL10, BOTTLE
Leo ($27): none
```

```javascript
class Product {
  constructor(name, price, kind) {
    this.name = name;
    this.price = price;
    this.kind = kind;
  }
}

class Order {
  constructor(customer, products) {
    this.customer = customer;
    this.products = products;
  }

  total() { return this.products.reduce((sum, product) => sum + product.price, 0); }
  has(kind) { return this.products.some((product) => product.kind === kind); }
}

// Every piece of a rule answers one question: qualifies(order).
// The leaves: each checks one thing about the order.
class TotalOver {
  constructor(amount) { this.amount = amount; }
  qualifies(order) { return order.total() > this.amount; }
}

class Has {
  constructor(kind) { this.kind = kind; }
  qualifies(order) { return order.has(this.kind); }
}

// The joins: each holds other pieces and asks them.
class And {
  constructor(left, right) { this.left = left; this.right = right; }
  qualifies(order) { return this.left.qualifies(order) && this.right.qualifies(order); }
}

class Or {
  constructor(left, right) { this.left = left; this.right = right; }
  qualifies(order) { return this.left.qualifies(order) || this.right.qualifies(order); }
}

class Not {
  constructor(rule) { this.rule = rule; }
  qualifies(order) { return !this.rule.qualifies(order); }
}

const boots = new Product("Hiking boots", 120, "shoe");
const jacket = new Product("Rain jacket", 80, "jacket");
const bottle = new Product("Water bottle", 15, "bottle");
const socks = new Product("Trail socks", 12, "socks");
const orders = [new Order("Maya", [boots, socks]), new Order("Sam", [jacket]), new Order("Leo", [bottle, socks])];

// Each rule is a tree of small pieces. The admin screen builds these from marketing's choices.
const rules = new Map([
  ["TRAIL10", new And(new TotalOver(50), new Or(new Has("shoe"), new Has("jacket")))],
  ["BOTTLE", new And(new Has("jacket"), new Not(new Has("bottle")))],
  ["BOOTS20", new And(new Has("shoe"), new TotalOver(100))],
]);
for (const order of orders) {
  const codes = [...rules.keys()].filter((code) => rules.get(code).qualifies(order));
  console.log(`${order.customer} ($${order.total()}): ${codes.join(", ") || "none"}`);
}
```

```text
Maya ($132): TRAIL10, BOOTS20
Sam ($80): TRAIL10, BOTTLE
Leo ($27): none
```

```typescript
class Product {
  name: string;
  price: number;
  kind: string;

  constructor(name: string, price: number, kind: string) {
    this.name = name;
    this.price = price;
    this.kind = kind;
  }
}

class Order {
  customer: string;
  products: Product[];

  constructor(customer: string, products: Product[]) {
    this.customer = customer;
    this.products = products;
  }

  total(): number { return this.products.reduce((sum, product) => sum + product.price, 0); }
  has(kind: string): boolean { return this.products.some((product) => product.kind === kind); }
}

// Every piece of a rule answers one question.
interface Rule {
  qualifies(order: Order): boolean;
}

// The leaves: each checks one thing about the order.
class TotalOver implements Rule {
  amount: number;
  constructor(amount: number) { this.amount = amount; }
  qualifies(order: Order): boolean { return order.total() > this.amount; }
}

class Has implements Rule {
  kind: string;
  constructor(kind: string) { this.kind = kind; }
  qualifies(order: Order): boolean { return order.has(this.kind); }
}

// The joins: each holds other pieces and asks them.
class And implements Rule {
  left: Rule;
  right: Rule;
  constructor(left: Rule, right: Rule) { this.left = left; this.right = right; }
  qualifies(order: Order): boolean { return this.left.qualifies(order) && this.right.qualifies(order); }
}

class Or implements Rule {
  left: Rule;
  right: Rule;
  constructor(left: Rule, right: Rule) { this.left = left; this.right = right; }
  qualifies(order: Order): boolean { return this.left.qualifies(order) || this.right.qualifies(order); }
}

class Not implements Rule {
  rule: Rule;
  constructor(rule: Rule) { this.rule = rule; }
  qualifies(order: Order): boolean { return !this.rule.qualifies(order); }
}

const boots = new Product("Hiking boots", 120, "shoe");
const jacket = new Product("Rain jacket", 80, "jacket");
const bottle = new Product("Water bottle", 15, "bottle");
const socks = new Product("Trail socks", 12, "socks");
const orders = [new Order("Maya", [boots, socks]), new Order("Sam", [jacket]), new Order("Leo", [bottle, socks])];

// Each rule is a tree of small pieces. The admin screen builds these from marketing's choices.
const rules = new Map<string, Rule>([
  ["TRAIL10", new And(new TotalOver(50), new Or(new Has("shoe"), new Has("jacket")))],
  ["BOTTLE", new And(new Has("jacket"), new Not(new Has("bottle")))],
  ["BOOTS20", new And(new Has("shoe"), new TotalOver(100))],
]);
for (const order of orders) {
  const codes = [...rules.keys()].filter((code) => rules.get(code)!.qualifies(order));
  console.log(`${order.customer} ($${order.total()}): ${codes.join(", ") || "none"}`);
}
```

```text
Maya ($132): TRAIL10, BOOTS20
Sam ($80): TRAIL10, BOTTLE
Leo ($27): none
```

Maya gets BOOTS20 now, and nobody wrote an `if` for it: it's three pieces snapped together. The admin screen builds trees like these from marketing's choices and saves them, so a new coupon is new data, and the loop that checks coupons never changes again.

C#'s primary constructors and Java's records keep each piece to one line; Python and JavaScript need no interface, because any object with a `qualifies` method will do.

## How it got its name

Teams building rule screens, search filters and query languages kept landing on this shape: a few kinds of piece, joined into a tree, where each piece knows what it means. The 1994 book of patterns called it the **Interpreter pattern**, because the tree *interprets* a little language: it works out what a rule means for one order. A little language made for one job, like these coupon rules, is a **domain-specific language**, or DSL ("domain" means the business area it's for). In your textbook, the checks are *terminal expressions*, the joins *nonterminal expressions*, the order the *context*, and the tree an *abstract syntax tree*.

You've seen the shape before: in *Composite: Boxes Inside Boxes*, a box and a pallet both answered "how much do you weigh?". Interpreter is a composite where each piece means something. And it's **polymorphism** at work: one call, `qualifies(order)`, answered five ways.

## The modern version: pieces as functions

A piece with one method is really a function, so the same trees can be built from functions that return functions:

```csharp
Product boots = new Product("Hiking boots", 120, "shoe");
Product jacket = new Product("Rain jacket", 80, "jacket");
Product bottle = new Product("Water bottle", 15, "bottle");
Product socks = new Product("Trail socks", 12, "socks");
List<Order> orders = new List<Order>
{
    new Order("Maya", new List<Product> { boots, socks }),
    new Order("Sam", new List<Product> { jacket }),
    new Order("Leo", new List<Product> { bottle, socks }),
};

// The same trees, built from functions instead of classes.
Dictionary<string, Func<Order, bool>> rules = new Dictionary<string, Func<Order, bool>>
{
    ["TRAIL10"] = AllOf(TotalOver(50), AnyOf(Has("shoe"), Has("jacket"))),
    ["BOTTLE"] = AllOf(Has("jacket"), NoneOf(Has("bottle"))),
    ["BOOTS20"] = AllOf(Has("shoe"), TotalOver(100)),
};
foreach (Order order in orders)
{
    List<string> codes = rules.Where(rule => rule.Value(order)).Select(rule => rule.Key).ToList();
    Console.WriteLine($"{order.Customer} (${order.Total()}): {(codes.Count > 0 ? string.Join(", ", codes) : "none")}");
}

// Each piece is a function that answers "does this order qualify?"
Func<Order, bool> TotalOver(int amount) => order => order.Total() > amount;
Func<Order, bool> Has(string kind) => order => order.Has(kind);
Func<Order, bool> AllOf(params Func<Order, bool>[] parts) => order => parts.All(part => part(order));
Func<Order, bool> AnyOf(params Func<Order, bool>[] parts) => order => parts.Any(part => part(order));
Func<Order, bool> NoneOf(params Func<Order, bool>[] parts) => order => !parts.Any(part => part(order));

record Product(string Name, int Price, string Kind);

record Order(string Customer, List<Product> Products)
{
    public int Total() => Products.Sum(product => product.Price);
    public bool Has(string kind) => Products.Any(product => product.Kind == kind);
}
```

```text
Maya ($132): TRAIL10, BOOTS20
Sam ($80): TRAIL10, BOTTLE
Leo ($27): none
```

```java
record Product(String name, int price, String kind) {}

record Order(String customer, List<Product> products) {
    int total() { return products.stream().mapToInt(Product::price).sum(); }
    boolean has(String kind) { return products.stream().anyMatch(product -> product.kind().equals(kind)); }
}

// Each piece is a function that answers "does this order qualify?"
// Java's Predicate already knows and, or and negate.
Predicate<Order> totalOver(int amount) { return order -> order.total() > amount; }
Predicate<Order> has(String kind) { return order -> order.has(kind); }

void main() {
    Product boots = new Product("Hiking boots", 120, "shoe");
    Product jacket = new Product("Rain jacket", 80, "jacket");
    Product bottle = new Product("Water bottle", 15, "bottle");
    Product socks = new Product("Trail socks", 12, "socks");
    List<Order> orders = List.of(
        new Order("Maya", List.of(boots, socks)),
        new Order("Sam", List.of(jacket)),
        new Order("Leo", List.of(bottle, socks)));

    // The same trees, built from functions instead of classes.
    Map<String, Predicate<Order>> rules = new LinkedHashMap<>();
    rules.put("TRAIL10", totalOver(50).and(has("shoe").or(has("jacket"))));
    rules.put("BOTTLE", has("jacket").and(has("bottle").negate()));
    rules.put("BOOTS20", has("shoe").and(totalOver(100)));
    for (Order order : orders) {
        List<String> codes = rules.keySet().stream().filter(code -> rules.get(code).test(order)).toList();
        IO.println(order.customer() + " ($" + order.total() + "): " + (codes.isEmpty() ? "none" : String.join(", ", codes)));
    }
}
```

```text
Maya ($132): TRAIL10, BOOTS20
Sam ($80): TRAIL10, BOTTLE
Leo ($27): none
```

```python
class Product:
    def __init__(self, name, price, kind):
        self.name = name
        self.price = price
        self.kind = kind


class Order:
    def __init__(self, customer, products):
        self.customer = customer
        self.products = products

    def total(self):
        return sum(product.price for product in self.products)

    def has(self, kind):
        return any(product.kind == kind for product in self.products)


# Each piece is a function that answers "does this order qualify?"
def total_over(amount):
    return lambda order: order.total() > amount


def has(kind):
    return lambda order: order.has(kind)


def all_of(*parts):
    return lambda order: all(part(order) for part in parts)


def any_of(*parts):
    return lambda order: any(part(order) for part in parts)


def none_of(*parts):
    return lambda order: not any(part(order) for part in parts)


boots = Product("Hiking boots", 120, "shoe")
jacket = Product("Rain jacket", 80, "jacket")
bottle = Product("Water bottle", 15, "bottle")
socks = Product("Trail socks", 12, "socks")
orders = [Order("Maya", [boots, socks]), Order("Sam", [jacket]), Order("Leo", [bottle, socks])]

# The same trees, built from functions instead of classes.
rules = {
    "TRAIL10": all_of(total_over(50), any_of(has("shoe"), has("jacket"))),
    "BOTTLE": all_of(has("jacket"), none_of(has("bottle"))),
    "BOOTS20": all_of(has("shoe"), total_over(100)),
}
for order in orders:
    codes = [code for code, rule in rules.items() if rule(order)]
    print(f"{order.customer} (${order.total()}): {', '.join(codes) or 'none'}")
```

```text
Maya ($132): TRAIL10, BOOTS20
Sam ($80): TRAIL10, BOTTLE
Leo ($27): none
```

```javascript
class Product {
  constructor(name, price, kind) {
    this.name = name;
    this.price = price;
    this.kind = kind;
  }
}

class Order {
  constructor(customer, products) {
    this.customer = customer;
    this.products = products;
  }

  total() { return this.products.reduce((sum, product) => sum + product.price, 0); }
  has(kind) { return this.products.some((product) => product.kind === kind); }
}

// Each piece is a function that answers "does this order qualify?"
const totalOver = (amount) => (order) => order.total() > amount;
const has = (kind) => (order) => order.has(kind);
const allOf = (...parts) => (order) => parts.every((part) => part(order));
const anyOf = (...parts) => (order) => parts.some((part) => part(order));
const noneOf = (...parts) => (order) => !parts.some((part) => part(order));

const boots = new Product("Hiking boots", 120, "shoe");
const jacket = new Product("Rain jacket", 80, "jacket");
const bottle = new Product("Water bottle", 15, "bottle");
const socks = new Product("Trail socks", 12, "socks");
const orders = [new Order("Maya", [boots, socks]), new Order("Sam", [jacket]), new Order("Leo", [bottle, socks])];

// The same trees, built from functions instead of classes.
const rules = new Map([
  ["TRAIL10", allOf(totalOver(50), anyOf(has("shoe"), has("jacket")))],
  ["BOTTLE", allOf(has("jacket"), noneOf(has("bottle")))],
  ["BOOTS20", allOf(has("shoe"), totalOver(100))],
]);
for (const order of orders) {
  const codes = [...rules.keys()].filter((code) => rules.get(code)(order));
  console.log(`${order.customer} ($${order.total()}): ${codes.join(", ") || "none"}`);
}
```

```text
Maya ($132): TRAIL10, BOOTS20
Sam ($80): TRAIL10, BOTTLE
Leo ($27): none
```

```typescript
class Product {
  name: string;
  price: number;
  kind: string;

  constructor(name: string, price: number, kind: string) {
    this.name = name;
    this.price = price;
    this.kind = kind;
  }
}

class Order {
  customer: string;
  products: Product[];

  constructor(customer: string, products: Product[]) {
    this.customer = customer;
    this.products = products;
  }

  total(): number { return this.products.reduce((sum, product) => sum + product.price, 0); }
  has(kind: string): boolean { return this.products.some((product) => product.kind === kind); }
}

// Each piece is a function that answers "does this order qualify?"
type Rule = (order: Order) => boolean;
const totalOver = (amount: number): Rule => (order) => order.total() > amount;
const has = (kind: string): Rule => (order) => order.has(kind);
const allOf = (...parts: Rule[]): Rule => (order) => parts.every((part) => part(order));
const anyOf = (...parts: Rule[]): Rule => (order) => parts.some((part) => part(order));
const noneOf = (...parts: Rule[]): Rule => (order) => !parts.some((part) => part(order));

const boots = new Product("Hiking boots", 120, "shoe");
const jacket = new Product("Rain jacket", 80, "jacket");
const bottle = new Product("Water bottle", 15, "bottle");
const socks = new Product("Trail socks", 12, "socks");
const orders = [new Order("Maya", [boots, socks]), new Order("Sam", [jacket]), new Order("Leo", [bottle, socks])];

// The same trees, built from functions instead of classes.
const rules = new Map<string, Rule>([
  ["TRAIL10", allOf(totalOver(50), anyOf(has("shoe"), has("jacket")))],
  ["BOTTLE", allOf(has("jacket"), noneOf(has("bottle")))],
  ["BOOTS20", allOf(has("shoe"), totalOver(100))],
]);
for (const order of orders) {
  const codes = [...rules.keys()].filter((code) => rules.get(code)!(order));
  console.log(`${order.customer} ($${order.total()}): ${codes.join(", ") || "none"}`);
}
```

```text
Maya ($132): TRAIL10, BOOTS20
Sam ($80): TRAIL10, BOTTLE
Leo ($27): none
```

`totalOver(50)` hands back a function that answers the question for any order, and each join hands back a function that asks the ones it was given. Java's `Predicate` already has `and`, `or` and `negate`; the other languages write `allOf`, `anyOf` and `noneOf` themselves. The functions are shorter; the classes are easier to save, print and inspect, which the next lesson needs.

## When the rules are typed as text

Some day marketing may want to type `total over 50 and (has shoe or has jacket)` instead of clicking. Then a **parser** turns the text into the tree; the pieces stay exactly as they are. For a handful of words, a short hand-written parser does. Once the language has brackets, an order of operations ("and" before "or") and needs clear messages ("expected a number after 'over'"), use a parser library: ANTLR works in all five of the course's languages, Lark in Python, and Peggy or Chevrotain in JavaScript and TypeScript.

## Where you've already used it

- **Regular expressions:** `\d{3}-\d{4}` is a little language. The regex engine reads it into a tree of pieces and asks each piece whether the text matches.
- **Formulas and filters:** a spreadsheet's `=IF(B2>50, "free shipping", "")`, a SQL `WHERE total > 50`, and an email app's search box, `from:maya has:attachment`, are rules written by users and interpreted by a program.
- **C#'s LINQ expression trees,** which a database library reads to build SQL, and **Java's `Predicate.and()`, `or()` and `negate()`**, which you saw above.

## When not to use it

- **When developers own the rules and they rarely change.** Two coupons a year read best as two plain `if`s.
- **When the language keeps growing**: variables, loops, functions. Then you're building a programming language. Use a parser library or an existing rules tool, or let users work in a language they already have, such as a spreadsheet.
- **When speed matters most.** Walking a tree is slower than running compiled code. That's fine for coupons, and the function version helps, since each rule is built once and then called.

The cost: a class for every kind of piece, and something (a screen or a parser) to build the trees.

**How often you'll meet it:** rarely, to write one yourself (our estimate: you'll *use* little languages every day, in regular expressions, SQL and formulas, but write one only now and then, mostly for rules, filters and search).

## Check yourself

2 questions to try on the lesson page.

## So what

When rules change faster than you can release code, and someone else writes them, make the rules data: a few pieces that each answer one question, snapped into a tree. The next lesson gives that same tree three new jobs.

## Key terms

- [Interpreter Pattern](https://www.ask-codey.com/glossary/interpreter-pattern)
- [Domain-Specific Language](https://www.ask-codey.com/glossary/domain-specific-language)
- [Polymorphism](https://www.ask-codey.com/glossary/polymorphism-oop)

## Cheat sheets

- [Interpreter: A Little Language for Rules](https://www.ask-codey.com/cheat-sheets/dp-interpreter-cheat-sheet)

Source: https://www.ask-codey.com/lessons/dp-interpreter
