> For AI agents: the complete documentation index is available at https://nhanbe.id.vn/llms.txt, the full documentation bundle is available at https://nhanbe.id.vn/llms-full.txt.

# Interpreter

## Overview

Define a grammar and an interpreter to evaluate expressions in that language.

## When to use

- You need a small, stable language for rules or filters.
- Expressions are simple and frequent.

## Java example

```java
interface Expression {
    boolean interpret(String context);
}

class ContainsExpression implements Expression {
    private final String token;
    ContainsExpression(String token) { this.token = token; }
    public boolean interpret(String context) {
        return context.contains(token);
    }
}
```

## TypeScript example

```ts
interface Expression {
  interpret(context: string): boolean;
}

class ContainsExpression implements Expression {
  constructor(private token: string) {}
  interpret(context: string): boolean {
    return context.includes(this.token);
  }
}
```

## Pros and cons

Pros:

- Easy to extend grammar with new expressions.
- Clear representation of rules.

Cons:

- Can become complex for large grammars.
- Performance can degrade with many nodes.

## Common pitfalls

- Using Interpreter for complex DSLs.
- Skipping caching for repeated evaluations.

## Related patterns

- [Strategy](https://nhanbe.id.vn/design-patterns/behavioral/strategy.md)
- [Composite](https://nhanbe.id.vn/design-patterns/structural/composite.md)
