Deep Dive
low level designdesign patternsoop

Interpreter Pattern: When Your Config Grows a Grammar

Feature-flag rules, search filters, and pricing conditions all quietly become little languages. The Interpreter pattern turns that grammar into a tree of classes that evaluate themselves — and tells you exactly when to stop and reach for a real parser instead.

·15 min read
Hard

It always starts as a boolean column. is_beta_user. Then product wants beta only for employees or early adopters, so the flag becomes a string you switch on. Then it’s employees-or-early-adopters but not in the EU, and someone ships a targeting_rule text field that a hand-rolled function parses with .split("&&"). Six months later that function is 300 lines, nobody trusts the operator precedence, and a marketing manager just typed a rule that silently evaluated to true for everyone.

What happened is subtle: your config file grew a language. beta AND (employee OR early_adopter) is a sentence in a small grammar with variables, AND, OR, NOT, and parentheses. The .split() mess is a parser and an evaluator tangled into one unmaintainable knot. The Gang of Four’s answer isn’t “write a better regex” — it’s “represent the grammar as a class hierarchy, and let the sentence become a tree that evaluates itself.”

The intuition: you already do this with arithmetic

Read 3 + 4 * 2 and you don’t scan left to right and get 14. Your brain builds a tree — multiplication binds tighter, so 4 * 2 is a subtree, and the + sits above it with 3 on the left. You evaluate the leaves, fold them into their parent, and fold up to the root: 4 * 2 → 8, then 3 + 8 → 11.

That mental tree is the Interpreter pattern. Each kind of node — a number, an addition, a multiplication — knows one thing: how to produce its own value given its children. Precedence isn’t a rule you re-check at evaluation time; it’s baked into the shape of the tree. Evaluation is nothing but recursion down that shape.

The tree is the whole idea — and the members-only continuation makes it concrete: the class diagram and full Expression/Var/And/Or/Not code, a walkthrough that builds a sentence and interprets it bottom-up against two different contexts, the exact line where parsing ends and interpreting begins, the real-world ASTs (SpEL, regex engines, SQL planners, flag targeting), the tradeoffs table for when to reach for a real parser instead, and an interview corner with a Basic Calculator challenge and a quiz.

Members only

Keep reading with Premium

You've reached the members-only part of this deep-dive — the full implementation, the interactive ring simulator, and the step-by-step walkthrough. Unlock it with a membership.

Related Articles