The Interpreter pattern is intended to provide you with a way to define representation of the grammar of a language whith an interpreter that uses the representation to interpret sentences in the language.

image

Some applications provide support for built-in scripting and macro languages so users can describe operations they can perform in the application. If this ability is what you want, then I am sorry to inform you: please use one of the many scripting engines available, for example CS-Script – The C# Script Engine.

The interpreter pattern is especially useful for parsing algorithmic expressions, but it is also very useful for interpretation of small strings containing foreign code. On the net you can find an abundance of examples that use the interpreter pattern for conversion of a Roman numeral to a decimal.

Nice as it is, but instead of ruminating the Roman example we will apply the interpreter pattern for conversion of binary code to decimal.

All you have to do in the client is to construct an interpretation tree, and later on to walk the tree with the provided context. The context contains all necessary information that is global to the interpreter.

In our case, the context contains a binary input and a decimal output. I know, these should be properties instead of global variables. So you should refactor them.

The base class AbstractExpression is the mother of all expressions. Maybe you should refactor it to an interface. In this example it contains one abstract method which receives the context.

As always the concrete class does all the work, conversion of binary code to decimal. It’s no rocket science, but nicely shows how this pattern works.

 

At this point you probably are thinking: Hey, where is the NonTerminalExpression? Honestly, I tried to use it in the example, but the example became a little bit to complex. So I purged it. On the other hand, you probably would not use it very often in real world situations, except for building a calculator.

The expression "5*(3+2)" contains the nonterminal expression "(3+2)". You could rewrite the expression like this:

If you want to try this yourself and incorporate a nonterminal expression, be my guest. I will wait right here for you. See you later, then.

This post is part of my series on the foundational design patterns in C#. In this series we explore the ancient design patterns and their use in real-world programming situations of today. In these series of posts we explore each pattern and look at simplified real-world C# code that implements the pattern.