Applied Design Patterns with Java

Behavioral :: Interpreter (243) {C ch 18}


Collaborations

Consequences

Interpreter has the following benefits and liabilities:

  1. It's easy to change and extend the grammar. Because the pattern uses classes to represent grammar rules, use inheritance to change or extend the grammar. Existing expressions can be modified incrementally, and new expressions can be defined as variations on old ones.
  2. Implementing the grammar is easy. Classes defining nodes in the abstract syntax tree have similar implementations. These classes are easy to write, and often their generation can be automated with a compiler or parser generator.
  3. Complex grammars are hard to maintain. The Interpreter pattern defines at least one class for every rule in the grammar (grammar rules defined using BNF may require multiple classes). Hence grammars containing many rules can be hard to manage and maintain. Other design patterns can be applied to mitigate the problem. But when the grammar is very complex, other techniques such as parser or compiler generators are more appropriate.
  4. Adding new ways to interpret expressions. The Interpreter pattern makes it easier to evaluate an expression in a new way. It's easy to support pretty printing or type-checking an expression by defining a new operation on the expression classes. To keep creating new ways of interpreting an expression, consider using the Visitor (331) pattern to avoid changing the grammar classes.

Catalog Behavioral Prev Next