Interpreter Pattern
Represent each rule of a small grammar as a class, build sentences as a tree of those objects, and evaluate the tree against a context.
Overview
The problem: rules that change faster than the code
A product team wants to switch a feature on for some users only: people in the US on the pro plan, or adults anywhere, but never beta testers. Next week the rule changes. If every rule is an if statement in the code, each change is a code review and a deploy. If the rule is a string run through Python's eval(), anyone who can edit the rule can run any code on your server; the Python docs warn that eval() with untrusted input leads to security vulnerabilities.
The middle path is a small language of your own. Rules are stored as text, such as country == 'US' and (plan == 'pro' or age >= 21) and not beta, and the program understands exactly that grammar and nothing more.
Put the three side by side and the trade is clear. Hard-coded if statements are low risk, but slow to change, because every change is a code change and a deploy. eval() on a stored string is fast to change, since you only edit the string, but any Python code can run. A small rule language, the Interpreter pattern, keeps the speed of editing a string while limiting the risk to only what the grammar allows.
Interview questions
- Show the smell Interpreter fixes, and the fix.
- How does Interpreter relate to Composite and Visitor?
- When should you not write your own interpreter?
- How do you make a rule interpreter fast?
- How do you keep a user-editable rule language safe?
Sign up free to read the full topic
More Low-Level Design topics
Start free on Cariara · Coding problems · System design studio