Save up to 75% on Flights

In this episode, we look at a behavioral pattern that is key for solving certain types of problems.  These happen to be grammar and translation applications.  Thus, the interpreter pattern gives us a way to do precisely that.  We use this to interpret text into a set of commands.

The Interpreter Pattern Defined

As always, we will start with the “Gang of Four” intent to set the stage for our discussion.

“Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language.”

This makes complete sense if you understand language grammars.  For the rest of us, let’s break this down a little bit through an example.  We will assume you are reading a text file where each line is a value and either add, update, or delete.  When you process it, you can break it down into a value and a command.  The most simple interpreter would be able to determine which is which for a given line then translate into something the application understands.  This may be a conversion to output or could be a method call and fill out parameters.

Applying The Pattern

There are a few different ways to implement this pattern, but they tend to boil down to a set of classes that form the grammar.  The classes may all implement a specific interface (for a translate or calculate method).  However, that is not required, just helpful.  The trick in this pattern is to make sure that the grammar classes are interchangeable enough to support the language.  Think about mathematical expressions as an example.  The interpreter must be able to support literals and operators in any order as well as nested.  The result will always be a tree (ouch flashbacks of diagramming sentences comes to mind).

Java, PHP, C#, etc.

The interpreter pattern is supported in all languages as a class and some use of an interface.  However, some environments provide a dynamic assessment of values and code often referred to as reflection.  When a language supports this feature, then it can allow for far more complex grammars.  On the other hand, those can become difficult to write and debug.  Although this is not one of the more common patterns, it is one that can be critical to a solution, and proper use of this can help advance your career.

Take $10 Off Your First Order w/code: SAVE10 - 728 x 90

Rob Broadhead

Rob is a founder of, and frequent contributor to, Develpreneur. This includes the Building Better Developers podcast. He is also a longtime student of technology as a developer, designer, and manager of software solutions. Rob is a founder and principle of RB Consulting and has managed to author a book about his family experiences.In his free time, he stays busy raising five children (although a few have grown into adults). When he has a chance to breathe, he is on the ice playing hockey to relax.

Leave a Reply