Pricing formula visitor
A pricing formula tree and three operations on it – evaluation, printing and simplification – as visitors. A new operation leaves the node classes untouched.
The shop platform lets the sales team define price formulas such as price * qty + shipping. A parser turns the text into a tree of Num, Var, Add and Mul nodes. More and more operations are needed on that tree: computing the result, printing it to the audit log, simplifying it before caching, with validation and SQL export on the roadmap. Adding yet another method to every node class would bloat them quickly. The Visitor pattern flips the layout: nodes only have accept(visitor) and every operation is a separate class with one method per node type.
Task
accept(visitor)in every node calls the visitor's method for its own type and passes itself (visitNum(this),visitAdd(this)and so on) – this is double dispatch.Evaluator(variables)computes the value; an unknown variable ends with the errorUnknown variable: <name>.Printerputs every operation in parentheses:((price * qty) + shipping); whole numbers without a fractional part (2, not2.0), others in the shortest form (1.25).Simplifierreturns a new tree, simplifying from the leaves up:Num op Num→Num(constant folding),x + 0,0 + x,x * 1,1 * x→x,x * 0,0 * x→0.
The original tree must not change.
| Formula | Simplified |
|---|---|
(2 + 3) * x | (5 * x) |
(x * 1) + 0 | x |
(price * 1) + (10 + 5) | (price + 15) |
The tests add their own visitors (collecting variable names, counting nodes) – they must work without changes in the node classes. Language differences: Python uses visit_num, visit_var… and ValueError; C# IExprVisitor<T> and KeyNotFoundException; Java ExprVisitor<R> with a generic <R> R accept(...) and IllegalArgumentException; in Go (no generics in 1.13) the methods return interface{}, Evaluator stores the first error in its Err field (unknown variable: <name>), and the ready-made Evaluate, Print and Simplify functions wrap the visitors.
Topics: Visitor
Related articles
- Visitor: new operations without changing classes
The Visitor pattern through a menu: dishes, drinks and sets stay untouched, while pricing, an allergen report or an export are separate visitor objects. Double dispatch, a comparison with pattern matching and code in five languages.