Interpreter
When you need to convert a data source from one form into another, you need to interpret it. It can be as simple as turning a binary data sequence into a list of text lines by looking for new-line characters.
As the complexity of the analysis function grows and the number of ways the analysis can be configured increases, the likelihood you have accidentally created a report processing or query language increases.
Translation of such a data stream can start with a
Instead of putting the whole filtering and action sequence into one method of
one class, introduce the
The GoF book describes the
The wording is complicated, and the language does not match our current way of thinking. It’s possibly more correct nowadays to say we represent intentions in the language rather than problems.
I want to avoid using terms like language or grammar as they confuse the pattern explanation since most software engineers don’t knowingly write DSLs any more1. Instead, I want to refer to objects converting, querying, or analysing other objects.
The first example in the GoF book uses a
The unique thing about interpreter-as-state is that the pattern uses structured objects to transform, query, process or interpret something else. The structured objects remain constant and unaffected during the evaluation. The context often remains unchanged, and the result is a new object.
The second example in the GoF book shows something different and perhaps easier
to comprehend. The second
The important thing about the monad is that this pattern adjusts the
structured objects based on the context and the
I am yet to discover examples where both change at the same time. Either the structure interprets the context or is interpreted in light of the context. This dichotomy seems relevant, so I distinguish between the two patterns as each appears to solve a different problem, even if the solutions look similar on the surface. It’s another pattern suffering from inappropriate aggregation due to the solution-oriented approach.
Both
So, instead of thinking about
A general misconception, and the third interpretation of the pattern, is that
the interpreter pattern is about writing a parser—even though the GoF book
explicitly states it is not.
The book doesn’t explain how to create the tree in the first place, but a
monad
“How do you want me to transform this for you?”
Since the advent of object-oriented design and programming, the number of explicit DSLs I’ve seen has reduced dramatically. But, because the interaction of objects with structure against streams of structured and unstructured data is, in effect, a DSL, the number of actual DSLs has increased. This gap in understanding has possibly held back the interpreter pattern from more mainstream use.