Bird
0
0

You need to design an interpreter for a simple arithmetic language supporting addition and multiplication. Which approach best applies the Interpreter pattern?

hard📝 Trade-off Q8 of 15
LLD - Behavioral Design Patterns — Part 2
You need to design an interpreter for a simple arithmetic language supporting addition and multiplication. Which approach best applies the Interpreter pattern?
AImplement a database to store arithmetic expressions.
BUse a single class to parse and compute expressions without separate grammar classes.
CCreate TerminalExpressions for numbers and NonterminalExpressions for '+' and '*' operators.
DStore all expressions as strings and evaluate using eval() function.
Step-by-Step Solution
Solution:
  1. Step 1: Understand Interpreter pattern structure

    TerminalExpressions represent numbers, NonterminalExpressions represent operators combining expressions.
  2. Step 2: Evaluate options

    Creating TerminalExpressions for numbers and NonterminalExpressions for '+' and '*' operators matches the pattern design. Implementing a database is unrelated, while using a single class or eval() do not separate grammar and interpretation.
  3. Final Answer:

    Create TerminalExpressions for numbers and NonterminalExpressions for '+' and '*' operators. -> Option C
  4. Quick Check:

    Interpreter pattern for arithmetic = Terminal + Nonterminal Expressions [OK]
Quick Trick: Use Terminal for numbers, Nonterminal for operators [OK]
Common Mistakes:
MISTAKES
  • Ignoring grammar separation
  • Using eval() instead of interpreter classes

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes