Patterns: behavior · 3 MIN READ
Interpreter: evaluate a deliberately small language
Model a grammar without treating arbitrary text as executable code.
Model a grammar without treating arbitrary text as executable code. Interpreter represents a grammar with expression nodes and evaluates them against a context. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.
Behavioral pattern · A MAP OF THE IDEA
- Parse and validate a bounded grammar
- Build expression nodes
- Evaluate against an explicit environment
Useful when
- A small rule language changes as data
- Rules need inspectable expression structure
Watch out
- Parser and diagnostics are additional work
- Untrusted rules need depth and cost limits
Implementation & operation cost: High
Fit depends on the task
Editorial suitability, not benchmarks or a universal ranking. Styles describe different axes and can be combined.
The design decision
Interpreter represents a grammar with expression nodes and evaluates them against a context. Small rule languages can make business conditions explicit. Parsing, validation and evaluation are separate responsibilities; do not confuse a tiny interpreter with safely running arbitrary user code.
A complete Go example
Read this program from the entry point and follow the calls shown in the diagram. The output is included at the end so you can check the behavior without a compiler.
package main
import (
"fmt"
)
type Expr interface{ Eval(map[string]bool) bool }
type Name string
func (n Name) Eval(env map[string]bool) bool { return env[string(n)] }
type And struct{ Left, Right Expr }
func (a And) Eval(env map[string]bool) bool { return a.Left.Eval(env) && a.Right.Eval(env) }
func main() {
rule := And{Left: Name("paid"), Right: Name("inStock")}
fmt.Println(rule.Eval(map[string]bool{"paid": true, "inStock": false}))
}
// Output:
// false
And evaluates two named conditions from an explicit environment and short-circuits on false. The program constructs an AST directly; it includes no parser. Unknown names currently mean false, which is a policy to validate rather than hide in a production rule system.
Tradeoffs and the simpler alternative
Keep a grammar small and bound input length, tree depth and evaluation cost for untrusted rules. A normal function is simpler when rules never change as data. Larger languages usually deserve a proper parser, type checker and diagnostics.
TAKE THIS WITH YOU
Evaluates a defined expression language against a context. Keep a grammar small and bound input length, tree depth and evaluation cost for untrusted rules. A normal function is simpler when rules never change as data. Larger languages usually deserve a proper parser, type checker and diagnostics.
Check your understanding
Which statement best describes Interpreter: evaluate a deliberately small language?
Go to the source
Progress stays in this browser. No account needed.