Interpreter

Post on 17-Jun-2015

915 views 4 download

Tags:

description

The slides from a presentation I did on the Interpreter design pattern at the Melbourne Patterns group.

transcript

InterpreterAbhijit HiremagalurCogent Consulting

Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language [GOF, 243]

DomainLanguageGrammar

Object Hierarchy

Composite + interpret()

Reverse Polish Notation

3 + 4 is expressed as

3 4 +

3 - 4 + 5

(3 - 4) + 5 or 3 - (4 +5)

Which one is it?

5 4 3 - + 5 (4 3 -) +

5 (1) +6

The code

‘41 2 1 - +’ equals 42

Stack what?

[](41) => [41](2) => [41, 2](1) => [41, 2, 1](-) => [41, 1](+) => [42]

Easy to implement, change & extend?

Doesn’t address parsing

Use something else if grammar is complex

Refactor to an Interpreter when...

“Numerous methods on a class combine elements of an

implicit language”

Replace Implicit Language with Interpreter [Kerievsky]

“Define classes for the elements of the implicit

language so that instances may be combined to form interpretable expressions.”

A.K.A ?

• Little language

• Macro

• Domain specific language

Domain Specific Language (DSL)

Internal vs External DSL

Spec productSpec = both(priceIsBelow(9.00f)).and(not(coloured(WHITE)));

Spec productSpec = parse(“price below 9.00f and not coloured white”);

Share symbols with Flyweight

Move operations to Visitor

The end.