Tutorials Design Patterns Mastery
Interpreter Pattern: Building domain-specific languages
On this page
The Interpreter Pattern
The Interpreter Pattern is used to define a grammatical representation for a language and an interpreter that uses the representation to interpret sentences in the language. It is the "Inner Language" pattern used for parsing complex mathematical expressions, regular expressions, or custom business rules engines.
1. Abstract Syntax Trees (AST)
The pattern breaks a sentence (e.g., "5 + 2 - 1") into a tree of expressions. High-level expressions (like Plus) internally call low-level expressions (like Number).
public interface IExpression { int Interpret(); }
public class AddExpression : IExpression
{
private IExpression _left, _right;
public int Interpret() => _left.Interpret() + _right.Interpret();
}
2. Why use it?
It makes your system extremely flexible. Instead of writing 100 if/else statements for every possible business rule, you define "Rule Components." Your users can then combine these components into a rule "Sentence" that your system interprets at runtime.
4. Interview Mastery
Q: "Is the Interpreter pattern the same as a Compiler?"
Architect Answer: "Not exactly. A **Compiler** translates code from one language to another (e.g., C# to IL). An **Interpreter** directly *Evaluates* the code as it reads it. The Interpreter pattern is a very high-level, simplified approach suitable for simple Domain Specific Languages (DSLs). For a full programming language, you would use more advanced tools like Antlr or Roslyn."