How can you extend an existing Interpreter pattern implementation to support variables with values in expressions?
hard📝 Trade-off Q9 of 15
LLD - Behavioral Design Patterns — Part 2
How can you extend an existing Interpreter pattern implementation to support variables with values in expressions?
ARemove NonterminalExpressions and interpret variables directly.
BAdd a Context class that stores variable values and modify interpret methods to use it.
CReplace all TerminalExpressions with hardcoded values.
DUse global variables instead of passing context.
Step-by-Step Solution
Solution:
Step 1: Understand variable support in Interpreter pattern
Variables require a Context to store their values accessible during interpretation.
Step 2: Analyze options
Adding a Context class that stores variable values and modify interpret methods to use it correctly adds support for variables. The other approaches like removing NonterminalExpressions, hardcoding values, or using globals break the pattern or are poor design.
Final Answer:
Add a Context class that stores variable values and modify interpret methods to use it. -> Option B
Quick Check:
Variable support = Context stores values [OK]
Quick Trick:Use Context to hold variable values in Interpreter [OK]
Common Mistakes:
MISTAKES
Hardcoding variable values
Using globals instead of Context
Master "Behavioral Design Patterns — Part 2" in LLD
9 interactive learning modes - each teaches the same concept differently