terminal

codeando_simple

terminal

menu

terminal

search_module

guest@codeandosimple: ~/system/search $ grep -r "" .

Press [ENTER] to execute search

Status

Engine: Ready

Database: Online

Index: V2.1.0_LATEST

bash -- cat interpreter.md
guest@codeandosimple: ~/blog/design-patterns $ cat interpreter.md

Interpreter Pattern_

// "Things are not said, they are done. Because when they are done, they say themselves" - Woody Allen

# Purpose

The Interpreter pattern provides a way to evaluate sentences in a language, allowing the interpretation of those sentences within the program.

Simply put: Like a translator that takes complicated instructions and turns them into simple steps we can follow.

# Problem

Need to process languages or expressions defined by grammar rules (compilers, rule engines, etc.).

# Solution

Implement a class for each grammar rule. Each rule is an expression that can be interpreted to evaluate the sentence.

# Abstract Syntax Tree (AST)

Key representation of the structure of an expression.

  • Leaf Nodes: Values or operands (numbers).

  • Internal Nodes: Operators (+, -).

Interpreter Nodes

# Structure

Interpreter UML Structure

# Participants

  • AbstractExpression: Declares an interpret operation.
  • TerminalExpression: Interpretation for terminal symbols.
  • NonTerminalExpression: Complex grammatical rules.
  • Context: Global information for interpretation.
  • Client: Builds the AST and invokes the interpretation.

# When to Use It

  • Languages representable as abstract syntax trees.

  • Interpreting simple notations or DSLs.

# Advantages

  • verified

    Flexibility: New types of expressions.

  • verified

    Extensibility: Easy to extend the grammar.

# Disadvantages

  • warning

    Complexity: Difficult for heavy grammars.

  • warning

    Performance: Interpretation is less efficient than compilation.

# Example: Math Expressions

Interpretation of "1 + 2". Decomposition into parts: constant, operator, constant.

Interpreter Example

# Java Code

interface Expression { int interpret(); }

class NumberExpression implements Expression {
    private int number;
    public int interpret() { return number; }
}

class AddExpression implements Expression {
    private Expression left, right;
    public int interpret() { return left.interpret() + right.interpret(); }
}

# Mapping Participants

  • Expression: AbstractExpression.
  • NumberExpression: TerminalExpression.
  • AddExpression: NonterminalExpression.
  • Client: Evaluator.

# Conclusions

Provides flexibility to build systems that need to dynamically "understand" structured inputs.

# Related Patterns

Composite

To build the abstract syntax tree.

Flyweight

To share instances of TerminalExpression.