Skip to content

Commit 58ec27d

Browse files
committed
docs: improve interpreter
1 parent 943f3fb commit 58ec27d

File tree

2 files changed

+103
-91
lines changed

2 files changed

+103
-91
lines changed

interpreter/README.md

Lines changed: 102 additions & 90 deletions
Original file line numberDiff line numberDiff line change
@@ -3,138 +3,134 @@ title: Interpreter
33
category: Behavioral
44
language: en
55
tag:
6-
- Gang of Four
6+
- Abstraction
7+
- Data transformation
8+
- Decoupling
9+
- Domain
10+
- Gang of Four
11+
- Polymorphism
12+
- Runtime
713
---
814

915
## Intent
1016

11-
Given a language, define a representation for its grammar along with an interpreter that uses the
12-
representation to interpret sentences in the language.
17+
The Interpreter pattern is used to define a grammatical representation for a language and provides an interpreter to deal with this grammar.
1318

1419
## Explanation
1520

1621
Real-world example
1722

18-
> The halfling kids are learning basic math at school. They start from the very basics "1 + 1",
19-
> "4 - 2", "5 + 5", and so forth.
23+
> Consider a calculator application designed to interpret and calculate expressions entered by users. The application uses the Interpreter pattern to parse and evaluate arithmetic expressions such as "5 + 3 * 2". Here, the Interpreter translates each part of the expression into objects that represent numbers and operations (like addition and multiplication). These objects follow a defined grammar that allows the application to understand and compute the result correctly based on the rules of arithmetic. Each element of the expression corresponds to a class in the program's structure, simplifying the parsing and evaluation process for any inputted arithmetic formula.
2024
2125
In plain words
2226

23-
> Interpreter pattern interprets sentences in the desired language.
27+
> The Interpreter design pattern defines a representation for a language's grammar along with an interpreter that uses the representation to interpret sentences in the language.
2428
2529
Wikipedia says
2630

27-
> In computer programming, the interpreter pattern is a design pattern that specifies how to
28-
> evaluate sentences in a language. The basic idea is to have a class for each symbol (terminal or
29-
> nonterminal) in a specialized computer language. The syntax tree of a sentence in the language
30-
> is an instance of the composite pattern and is used to evaluate (interpret) the sentence for
31-
> a client.
31+
> In computer programming, the interpreter pattern is a design pattern that specifies how to evaluate sentences in a language. The basic idea is to have a class for each symbol (terminal or nonterminal) in a specialized computer language. The syntax tree of a sentence in the language is an instance of the composite pattern and is used to evaluate (interpret) the sentence for a client.
3232
3333
**Programmatic example**
3434

35-
To be able to interpret basic math, we need a hierarchy of expressions. The basic abstraction for
36-
it is the `Expression` class.
35+
To be able to interpret basic math, we need a hierarchy of expressions. The basic abstraction for it is the `Expression` class.
3736

3837
```java
3938
public abstract class Expression {
4039

41-
public abstract int interpret();
40+
public abstract int interpret();
4241

43-
@Override
44-
public abstract String toString();
42+
@Override
43+
public abstract String toString();
4544
}
4645
```
4746

48-
The simplest of the expressions is the `NumberExpression` that contains only a single integer
49-
number.
47+
The simplest of the expressions is the `NumberExpression` that contains only a single integer number.
5048

5149
```java
5250
public class NumberExpression extends Expression {
5351

54-
private final int number;
52+
private final int number;
5553

56-
public NumberExpression(int number) {
57-
this.number = number;
58-
}
54+
public NumberExpression(int number) {
55+
this.number = number;
56+
}
5957

60-
public NumberExpression(String s) {
61-
this.number = Integer.parseInt(s);
62-
}
58+
public NumberExpression(String s) {
59+
this.number = Integer.parseInt(s);
60+
}
6361

64-
@Override
65-
public int interpret() {
66-
return number;
67-
}
62+
@Override
63+
public int interpret() {
64+
return number;
65+
}
6866

69-
@Override
70-
public String toString() {
71-
return "number";
72-
}
67+
@Override
68+
public String toString() {
69+
return "number";
70+
}
7371
}
7472
```
7573

76-
The more complex expressions are operations such as `PlusExpression`, `MinusExpression`, and
77-
`MultiplyExpression`. Here's the first of them, the others are similar.
74+
The more complex expressions are operations such as `PlusExpression`, `MinusExpression`, and `MultiplyExpression`. Here's the first of them, the others are similar.
7875

7976
```java
8077
public class PlusExpression extends Expression {
8178

82-
private final Expression leftExpression;
83-
private final Expression rightExpression;
79+
private final Expression leftExpression;
80+
private final Expression rightExpression;
8481

85-
public PlusExpression(Expression leftExpression, Expression rightExpression) {
86-
this.leftExpression = leftExpression;
87-
this.rightExpression = rightExpression;
88-
}
82+
public PlusExpression(Expression leftExpression, Expression rightExpression) {
83+
this.leftExpression = leftExpression;
84+
this.rightExpression = rightExpression;
85+
}
8986

90-
@Override
91-
public int interpret() {
92-
return leftExpression.interpret() + rightExpression.interpret();
93-
}
87+
@Override
88+
public int interpret() {
89+
return leftExpression.interpret() + rightExpression.interpret();
90+
}
9491

95-
@Override
96-
public String toString() {
97-
return "+";
98-
}
92+
@Override
93+
public String toString() {
94+
return "+";
95+
}
9996
}
10097
```
10198

102-
Now we are able to show the interpreter pattern in action parsing some simple math.
99+
Now, we are able to show the interpreter pattern in action parsing some simple math.
103100

104101
```java
105-
// the halfling kids are learning some basic math at school
106-
// define the math string we want to parse
107-
final var tokenString = "4 3 2 - 1 + *";
108-
109-
// the stack holds the parsed expressions
110-
var stack = new Stack<Expression>();
111-
112-
// tokenize the string and go through them one by one
113-
var tokenList = tokenString.split(" ");
114-
for (var s : tokenList) {
115-
if (isOperator(s)) {
116-
// when an operator is encountered we expect that the numbers can be popped from the top of
117-
// the stack
118-
var rightExpression = stack.pop();
119-
var leftExpression = stack.pop();
120-
LOGGER.info("popped from stack left: {} right: {}",
121-
leftExpression.interpret(), rightExpression.interpret());
122-
var operator = getOperatorInstance(s, leftExpression, rightExpression);
123-
LOGGER.info("operator: {}", operator);
124-
var result = operator.interpret();
125-
// the operation result is pushed on top of the stack
126-
var resultExpression = new NumberExpression(result);
127-
stack.push(resultExpression);
128-
LOGGER.info("push result to stack: {}", resultExpression.interpret());
129-
} else {
130-
// numbers are pushed on top of the stack
131-
var i = new NumberExpression(s);
132-
stack.push(i);
133-
LOGGER.info("push to stack: {}", i.interpret());
134-
}
102+
// the halfling kids are learning some basic math at school
103+
// define the math string we want to parse
104+
final var tokenString="4 3 2 - 1 + *";
105+
106+
// the stack holds the parsed expressions
107+
var stack = new Stack<Expression>();
108+
109+
// tokenize the string and go through them one by one
110+
var tokenList = tokenString.split(" ");
111+
for (var s : tokenList) {
112+
if(isOperator(s)) {
113+
// when an operator is encountered we expect that the numbers can be popped from the top of
114+
// the stack
115+
var rightExpression = stack.pop();
116+
var leftExpression = stack.pop();
117+
LOGGER.info("popped from stack left: {} right: {}", leftExpression.interpret(),rightExpression.interpret());
118+
var operator = getOperatorInstance(s, leftExpression, rightExpression);
119+
LOGGER.info("operator: {}", operator);
120+
var result = operator.interpret();
121+
// the operation result is pushed on top of the stack
122+
var resultExpression = new NumberExpression(result);
123+
stack.push(resultExpression);
124+
LOGGER.info("push result to stack: {}", resultExpression.interpret());
125+
} else {
126+
// numbers are pushed on top of the stack
127+
var i = new NumberExpression(s);
128+
stack.push(i);
129+
LOGGER.info("push to stack: {}", i.interpret());
135130
}
136-
// in the end, the final result lies on top of the stack
137-
LOGGER.info("result: {}", stack.pop().interpret());
131+
}
132+
// in the end, the final result lies on top of the stack
133+
LOGGER.info("result: {}",stack.pop().interpret());
138134
```
139135

140136
Executing the program produces the following console output.
@@ -151,26 +147,42 @@ result: 8
151147

152148
## Class diagram
153149

154-
![alt text](./etc/interpreter_1.png "Interpreter")
150+
![Interpreter](./etc/interpreter_1.png "Interpreter")
155151

156152
## Applicability
157153

158-
Use the Interpreter pattern when there is a language to interpret, and you can represent statements
159-
in the language as abstract syntax trees. The Interpreter pattern works best when
154+
Use the Interpreter pattern when there is a language to interpret, and you can represent statements in the language as abstract syntax trees. The Interpreter pattern works best when
160155

161-
* The grammar is simple. For complex grammars, the class hierarchy for the grammar becomes large and unmanageable. Tools such as parser generators are a better alternative in such cases. They can interpret expressions without building abstract syntax trees, which can save space and possibly time
162-
* Efficiency is not a critical concern. The most efficient interpreters are usually not implemented by interpreting parse trees directly but by first translating them into another form. For example, regular expressions are often transformed into state machines. But even then, the translator can be implemented by the Interpreter pattern, so the pattern is still applicable
156+
* The grammar is simple. For complex grammars, the class hierarchy for the grammar becomes large and unmanageable. Tools such as parser generators are a better alternative in such cases. They can interpret expressions without building abstract syntax trees, which can save space and possibly time.
157+
* Efficiency is not a critical concern. The most efficient interpreters are usually not implemented by interpreting parse trees directly but by first translating them into another form. For example, regular expressions are often transformed into state machines. But even then, the translator can be implemented by the Interpreter pattern, so the pattern is still applicable.
163158

164159
## Known uses
165160

166161
* [java.util.Pattern](http://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html)
167162
* [java.text.Normalizer](http://docs.oracle.com/javase/8/docs/api/java/text/Normalizer.html)
168163
* All subclasses of [java.text.Format](http://docs.oracle.com/javase/8/docs/api/java/text/Format.html)
169164
* [javax.el.ELResolver](http://docs.oracle.com/javaee/7/api/javax/el/ELResolver.html)
165+
* SQL parsers in various database management systems.
166+
167+
## Consequences
168+
169+
Benefits:
170+
171+
* Adds new operations to interpret expressions easily without changing the grammar or classes of data.
172+
* Implements grammar directly in the language, making it easy to modify or extend.
173+
174+
Trade-offs:
175+
176+
* Can become complex and inefficient for large grammars.
177+
* Each rule in the grammar results in a class, leading to a large number of classes for complex grammars.
178+
179+
## Related Patterns
170180

181+
* [Composite](https://java-design-patterns.com/patterns/composite/): Often used together, where the Interpreter pattern leverages the Composite pattern to represent the grammar as a tree structure.
182+
* [Flyweight](https://java-design-patterns.com/patterns/flyweight/): Useful for sharing state to reduce memory usage in the Interpreter pattern, particularly for interpreters that deal with repetitive elements in a language.
171183

172184
## Credits
173185

174-
* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59)
175-
* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b)
176-
* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7)
186+
* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
187+
* [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq)
188+
* [Refactoring to Patterns](https://amzn.to/3VOO4F5)

interpreter/src/test/java/com/iluwatar/interpreter/NumberExpressionTest.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ public NumberExpressionTest() {
6060
*/
6161
@ParameterizedTest
6262
@MethodSource("expressionProvider")
63-
void testFromString(NumberExpression first) throws Exception {
63+
void testFromString(NumberExpression first) {
6464
final var expectedValue = first.interpret();
6565
final var testStringValue = String.valueOf(expectedValue);
6666
final var numberExpression = new NumberExpression(testStringValue);

0 commit comments

Comments
 (0)