SlideShare a Scribd company logo
1 of 41
Download to read offline
Domain Specific
         Languages
spkr.name = 'Venkat Subramaniam'
spkr.company = 'Agile Developer, Inc.'
                                                   DSL
spkr.credentials = %w{Programmer Trainer Author}
spkr.blog = 'agiledeveloper.com/blog'
spkr.email = 'venkats@agiledeveloper.com'
Abstract
Domain Specific Languages or DSLs are languages that
target a specific kind of problem or domain. We've had
various degree of success with DSLs, over the past several
years, in narrow areas. However, DSLs are not widely used
in general purpose application partly because the popular
widely used languages today do not make it easy.

In this presentation we will introduce DSLs, delve into their
benefits. We will look at a number of examples as to how we
can utilize them for common application tasks. We will take
a look at what language developments, tools, and techniques
are in the horizon that could bring this to common place.



                                                                2
Domain and Context
What’s Domain?

  It is an area of sphere of knowledge,
  influence, or activity

What’s Context?

  A logical framework within which
  we evolve models

What’s Bounded Context?
                                          Context
  Defines a logical boundary of
  relevance within the context
                                          Domain
                                                    3
Domain Specific Language
  What’s DSL?

   A language targeted at a particular type of problem

   Syntax focuses on intended domain/problem

   Unlike a general purpose language, you can’t use it
   for all kinds of stuff (or don’t want to)

   Limited in scope and capability

   Hence, they’re small and simple


                                                         4
External vs Internal
External DSL

  You define a new language

  You then parse the commands to take actions

  Can be lot of fun ;)

  One of my first jobs was to maintain lex and Yacc...

Internal DSL

  Constructs of a language are construed to form a DSL

  You don’t need to write an separate parser

  Commands tactfully map over to constructs like methods, etc.

  Also known an Embedded DSL
                                                                 5
External or Internal

It depends on your application

Certain languages are better suited for internal DSLs

  Smalltalk, Lisp, Ruby, Groovy, ...

Other languages are better suited for external DSL and
offer good parsing libraries or capabilities

  C++, Java, C#, ...



                                                         6
Characteristics of a DSL

What are some of the qualities of a DSL?

  Context Driven

    Extremely context sensitive

  Fluent Interfaces

    Provides for a humane, easy to understand interface




                                                          7
Context Driven


DSL is extremely context sensitive or context driven

A lot of things are knows from the context

Without context, we may be confused or misled

With context, there is less clutter, terse, but readable




                                                           8
Context Driven ...
I heard my friend Neal Ford yell out

  Venti Latte with 2 Extra Shots

What’s he talking about?

He’s using the Starbucks DSL

Nowhere did he mention the word coffee, but he sure
got a good one at a high price ;)

That’s context driven


                                                      9
Context Driven ...
I heard my friend Scott Davis mutter

  place a $ in a GString

What’s he talking about?

You don’t want to know

He sure was talking about embedding variables into the
Groovy’s mutable string class

That’s also context driven :)


                                                    10
Fluent Interface

I was going to call this hygienic interface

I like the name Eric Evans and Martin Fowler promote–
Fluent Interface/Humane Interface

It’s designed to be readable and to flow naturally

Not easy to design–you put in more effort to create it,
so it is easier for users to use



                                                          11
A Little Compromise
Command Query Separation was promoted by
Bertrand Meyer

  Command methods—mutators or modifiers—affect
  object state and don’t return anything

  Query methods—don’t affect object state and return
  useful information

You compromise a little to be fluent (kind of like words
bent to rhyme in a poem)

Command methods return self or a promoter for a good
flow

                                                       12
Fluent Loops




               13
Fluent Interface in
    EasyMock




                      14
Fluent Interface in
JSONObject Library




                       15
Fluency in Rails/Active Records




                             16
Fluency in Grails/GORM




                         17
Let’s Order Pizza
Voice on line (VOL): Thanks for calling Joe’s

You: Ya, A Large Thin Crust

VOL: Toppings?

You: Olives, Onions, Bell Pepper

VOL: Address

You: 101 Main St.,...

VOL: Card?

You: Visa 1234-1234-1234-1234

VOL: 20 minutes–Thank you
                                                18
Java Pizza Order


Not fluent

Very noisy—how many times do you have to say
joes_pizza?

Can we make it fluent?



                                               19
with
Some languages have a with keyword

within the scope, methods are invoked on an
implicit object

Here is an example from JavaScript




                                              20
with in Groovy?
Groovy has no with like
JavaScript

But we can hack!

The following does not
support nested with, but you
can use a stack to support it




                                21
Let’s use JS to Order Pizza




                          22
How about Fluent Java?



Less clutter

There is a context in each call

Each set method (except setCard()) returns this
(PizzaShop)

Can we make this a bit more readable?

                                                  23
A bit more Fluent...



Method names make sense in the flow, but may not
make sense alone

What’s a catch?



                                                  24
Ordered vs. Unordered
Some DSLs may require a certain order in the flow

  You can force ordering by tactfully defining return
  types that will allow method chaining in only
  certain order

     Not easy

Others may not require ordering

It depends on the particular problem

Ideally, not requiring an order is great, but may not
always be possible

                                                        25
How to Enforce Sequence?




                       26
Closures Make It Easier




                          27
Use A Builder

Do you have to burden your class with fluent interface?

Nope

You may create a builder or facade that will provide a
fluent interface

Users can use the builder to interact instead of the
underlying class




                                                       28
Creating DSLs
You may use tools like Antlr for working with DSLs

JetBrains is working on Meta Programming System
(MPS)

Languages like Ruby and Groovy may it easier to
create (internal) DSLs

What makes Groovy attractive?

  Classes are always open

  Closures and Builders

  Categories and ExpandoMetaClass

  To some extent operator overloading

  Parenthesis are almost optional (a bit lacking)    29
External DSLs Example


Ant is a good example of an external DSL

  The domain here is build

Ant parses your build commands

Can’t exploit full capability of Java, however

So, somewhat limiting or hard to extend

                                                 30
Internal DSLs Example




Pure Ruby syntax       Gant similarly is pure Groovy
Parsed by Ruby—no external parsing

You can do as much Ruby in it as you like        31
Groovy Builder: XML




                      32
Groovy Builder: Swing




                        33
Creating a DSL in Groovy




                       34
Using Categories


Type conversions
------------------------
2       => int
.days => int
.ago => Calendar
.at => Date


                             35
Using Expando




                36
Using Expando...




                   37
Categories vs.
ExpandoMetaClass
Categories allows you to tactically enhance a
class

ExpandoMetaClass is far reaching, global in
nature

You may not want to affect a class globally

Categories provide controlled flexibility


                                                38
Quiz Time




            39
References
A number of references from the following URL

http://martinfowler.com/bliki/DomainSpecificLanguage.html

http://docs.codehaus.org/display/GROOVY/Writing+Domain-
Specific+Languages

http://docs.codehaus.org/display/GROOVY/Gant

http://groovy.codehaus.org/ExpandoMetaClass

http://www.onboard.jetbrains.com/is1/articles/04/10/
lop/

http://www.jetbrains.com/mps
                                                           40
Thank You!


http://www.agiledeveloper.com — download
                                           41

More Related Content

Viewers also liked (6)

Defining DSL (Domain Specific Language) using Ruby
Defining DSL (Domain Specific Language) using RubyDefining DSL (Domain Specific Language) using Ruby
Defining DSL (Domain Specific Language) using Ruby
 
Hieber - An Introduction to Typology, Part I: Morphological Typology
Hieber - An Introduction to Typology, Part I: Morphological TypologyHieber - An Introduction to Typology, Part I: Morphological Typology
Hieber - An Introduction to Typology, Part I: Morphological Typology
 
Venkat Subramaniam Blending Java With Dynamic Languages
Venkat Subramaniam Blending Java With Dynamic LanguagesVenkat Subramaniam Blending Java With Dynamic Languages
Venkat Subramaniam Blending Java With Dynamic Languages
 
Remy Sharp The DOM scripting toolkit jQuery
Remy Sharp The DOM scripting toolkit jQueryRemy Sharp The DOM scripting toolkit jQuery
Remy Sharp The DOM scripting toolkit jQuery
 
Randy Shoup eBays Architectural Principles
Randy Shoup eBays Architectural PrinciplesRandy Shoup eBays Architectural Principles
Randy Shoup eBays Architectural Principles
 
Aspect Orientated Programming in Ruby
Aspect Orientated Programming in RubyAspect Orientated Programming in Ruby
Aspect Orientated Programming in Ruby
 

Similar to Domain Specific Languages

Bdd and dsl как способ построения коммуникации на проекте
Bdd and dsl как способ построения коммуникации на проектеBdd and dsl как способ построения коммуникации на проекте
Bdd and dsl как способ построения коммуникации на проекте
ISsoft
 
Agile DSL Development in Ruby
Agile DSL Development in RubyAgile DSL Development in Ruby
Agile DSL Development in Ruby
elliando dias
 
Os Alrubaie Ruby
Os Alrubaie RubyOs Alrubaie Ruby
Os Alrubaie Ruby
oscon2007
 
Challenges In Dsl Design
Challenges In Dsl DesignChallenges In Dsl Design
Challenges In Dsl Design
Sven Efftinge
 
Building DSLs On CLR and DLR (Microsoft.NET)
Building DSLs On CLR and DLR (Microsoft.NET)Building DSLs On CLR and DLR (Microsoft.NET)
Building DSLs On CLR and DLR (Microsoft.NET)
Vitaly Baum
 

Similar to Domain Specific Languages (20)

Building DSLs: Marriage of High Essence and Groovy Metaprogramming
Building DSLs: Marriage of High Essence and Groovy MetaprogrammingBuilding DSLs: Marriage of High Essence and Groovy Metaprogramming
Building DSLs: Marriage of High Essence and Groovy Metaprogramming
 
Bdd and dsl как способ построения коммуникации на проекте
Bdd and dsl как способ построения коммуникации на проектеBdd and dsl как способ построения коммуникации на проекте
Bdd and dsl как способ построения коммуникации на проекте
 
BDD or DSL как способ построения коммуникации на проекте - опыт комплексного ...
BDD or DSL как способ построения коммуникации на проекте - опыт комплексного ...BDD or DSL как способ построения коммуникации на проекте - опыт комплексного ...
BDD or DSL как способ построения коммуникации на проекте - опыт комплексного ...
 
Agile DSL Development in Ruby
Agile DSL Development in RubyAgile DSL Development in Ruby
Agile DSL Development in Ruby
 
Writing Readable Code
Writing Readable CodeWriting Readable Code
Writing Readable Code
 
C c#
C c#C c#
C c#
 
Groovy DSL
Groovy DSLGroovy DSL
Groovy DSL
 
Os Alrubaie Ruby
Os Alrubaie RubyOs Alrubaie Ruby
Os Alrubaie Ruby
 
difference between c c++ c#
difference between c c++ c#difference between c c++ c#
difference between c c++ c#
 
Enlightenment: A Cross Platform Window Manager & Toolkit
Enlightenment: A Cross Platform Window Manager & ToolkitEnlightenment: A Cross Platform Window Manager & Toolkit
Enlightenment: A Cross Platform Window Manager & Toolkit
 
Metamorphic Domain-Specific Languages
Metamorphic Domain-Specific LanguagesMetamorphic Domain-Specific Languages
Metamorphic Domain-Specific Languages
 
Challenges In Dsl Design
Challenges In Dsl DesignChallenges In Dsl Design
Challenges In Dsl Design
 
groovy DSLs from beginner to expert
groovy DSLs from beginner to expertgroovy DSLs from beginner to expert
groovy DSLs from beginner to expert
 
JBoss Forge - Breaking new ground in developer productivity
JBoss Forge - Breaking new ground in developer productivityJBoss Forge - Breaking new ground in developer productivity
JBoss Forge - Breaking new ground in developer productivity
 
How to Implement Domain Driven Design in Real Life SDLC
How to Implement Domain Driven Design  in Real Life SDLCHow to Implement Domain Driven Design  in Real Life SDLC
How to Implement Domain Driven Design in Real Life SDLC
 
WebAssembly: Digging a bit deeper
WebAssembly: Digging a bit deeperWebAssembly: Digging a bit deeper
WebAssembly: Digging a bit deeper
 
Building DSLs On CLR and DLR (Microsoft.NET)
Building DSLs On CLR and DLR (Microsoft.NET)Building DSLs On CLR and DLR (Microsoft.NET)
Building DSLs On CLR and DLR (Microsoft.NET)
 
Envisioning the Future of Language Workbenches
Envisioning the Future of Language WorkbenchesEnvisioning the Future of Language Workbenches
Envisioning the Future of Language Workbenches
 
Configuration as Code in Bamboo
Configuration as Code in BambooConfiguration as Code in Bamboo
Configuration as Code in Bamboo
 
Database Refactoring
Database RefactoringDatabase Refactoring
Database Refactoring
 

More from elliando dias

Why you should be excited about ClojureScript
Why you should be excited about ClojureScriptWhy you should be excited about ClojureScript
Why you should be excited about ClojureScript
elliando dias
 
Nomenclatura e peças de container
Nomenclatura  e peças de containerNomenclatura  e peças de container
Nomenclatura e peças de container
elliando dias
 
Polyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better AgilityPolyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better Agility
elliando dias
 
Javascript Libraries
Javascript LibrariesJavascript Libraries
Javascript Libraries
elliando dias
 
How to Make an Eight Bit Computer and Save the World!
How to Make an Eight Bit Computer and Save the World!How to Make an Eight Bit Computer and Save the World!
How to Make an Eight Bit Computer and Save the World!
elliando dias
 
A Practical Guide to Connecting Hardware to the Web
A Practical Guide to Connecting Hardware to the WebA Practical Guide to Connecting Hardware to the Web
A Practical Guide to Connecting Hardware to the Web
elliando dias
 
Introdução ao Arduino
Introdução ao ArduinoIntrodução ao Arduino
Introdução ao Arduino
elliando dias
 
Incanter Data Sorcery
Incanter Data SorceryIncanter Data Sorcery
Incanter Data Sorcery
elliando dias
 
Fab.in.a.box - Fab Academy: Machine Design
Fab.in.a.box - Fab Academy: Machine DesignFab.in.a.box - Fab Academy: Machine Design
Fab.in.a.box - Fab Academy: Machine Design
elliando dias
 
Hadoop - Simple. Scalable.
Hadoop - Simple. Scalable.Hadoop - Simple. Scalable.
Hadoop - Simple. Scalable.
elliando dias
 
Hadoop and Hive Development at Facebook
Hadoop and Hive Development at FacebookHadoop and Hive Development at Facebook
Hadoop and Hive Development at Facebook
elliando dias
 
Multi-core Parallelization in Clojure - a Case Study
Multi-core Parallelization in Clojure - a Case StudyMulti-core Parallelization in Clojure - a Case Study
Multi-core Parallelization in Clojure - a Case Study
elliando dias
 

More from elliando dias (20)

Clojurescript slides
Clojurescript slidesClojurescript slides
Clojurescript slides
 
Why you should be excited about ClojureScript
Why you should be excited about ClojureScriptWhy you should be excited about ClojureScript
Why you should be excited about ClojureScript
 
Functional Programming with Immutable Data Structures
Functional Programming with Immutable Data StructuresFunctional Programming with Immutable Data Structures
Functional Programming with Immutable Data Structures
 
Nomenclatura e peças de container
Nomenclatura  e peças de containerNomenclatura  e peças de container
Nomenclatura e peças de container
 
Geometria Projetiva
Geometria ProjetivaGeometria Projetiva
Geometria Projetiva
 
Polyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better AgilityPolyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better Agility
 
Javascript Libraries
Javascript LibrariesJavascript Libraries
Javascript Libraries
 
How to Make an Eight Bit Computer and Save the World!
How to Make an Eight Bit Computer and Save the World!How to Make an Eight Bit Computer and Save the World!
How to Make an Eight Bit Computer and Save the World!
 
Ragel talk
Ragel talkRagel talk
Ragel talk
 
A Practical Guide to Connecting Hardware to the Web
A Practical Guide to Connecting Hardware to the WebA Practical Guide to Connecting Hardware to the Web
A Practical Guide to Connecting Hardware to the Web
 
Introdução ao Arduino
Introdução ao ArduinoIntrodução ao Arduino
Introdução ao Arduino
 
Minicurso arduino
Minicurso arduinoMinicurso arduino
Minicurso arduino
 
Incanter Data Sorcery
Incanter Data SorceryIncanter Data Sorcery
Incanter Data Sorcery
 
Rango
RangoRango
Rango
 
Fab.in.a.box - Fab Academy: Machine Design
Fab.in.a.box - Fab Academy: Machine DesignFab.in.a.box - Fab Academy: Machine Design
Fab.in.a.box - Fab Academy: Machine Design
 
The Digital Revolution: Machines that makes
The Digital Revolution: Machines that makesThe Digital Revolution: Machines that makes
The Digital Revolution: Machines that makes
 
Hadoop + Clojure
Hadoop + ClojureHadoop + Clojure
Hadoop + Clojure
 
Hadoop - Simple. Scalable.
Hadoop - Simple. Scalable.Hadoop - Simple. Scalable.
Hadoop - Simple. Scalable.
 
Hadoop and Hive Development at Facebook
Hadoop and Hive Development at FacebookHadoop and Hive Development at Facebook
Hadoop and Hive Development at Facebook
 
Multi-core Parallelization in Clojure - a Case Study
Multi-core Parallelization in Clojure - a Case StudyMulti-core Parallelization in Clojure - a Case Study
Multi-core Parallelization in Clojure - a Case Study
 

Recently uploaded

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 

Recently uploaded (20)

Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 

Domain Specific Languages

  • 1. Domain Specific Languages spkr.name = 'Venkat Subramaniam' spkr.company = 'Agile Developer, Inc.' DSL spkr.credentials = %w{Programmer Trainer Author} spkr.blog = 'agiledeveloper.com/blog' spkr.email = 'venkats@agiledeveloper.com'
  • 2. Abstract Domain Specific Languages or DSLs are languages that target a specific kind of problem or domain. We've had various degree of success with DSLs, over the past several years, in narrow areas. However, DSLs are not widely used in general purpose application partly because the popular widely used languages today do not make it easy. In this presentation we will introduce DSLs, delve into their benefits. We will look at a number of examples as to how we can utilize them for common application tasks. We will take a look at what language developments, tools, and techniques are in the horizon that could bring this to common place. 2
  • 3. Domain and Context What’s Domain? It is an area of sphere of knowledge, influence, or activity What’s Context? A logical framework within which we evolve models What’s Bounded Context? Context Defines a logical boundary of relevance within the context Domain 3
  • 4. Domain Specific Language What’s DSL? A language targeted at a particular type of problem Syntax focuses on intended domain/problem Unlike a general purpose language, you can’t use it for all kinds of stuff (or don’t want to) Limited in scope and capability Hence, they’re small and simple 4
  • 5. External vs Internal External DSL You define a new language You then parse the commands to take actions Can be lot of fun ;) One of my first jobs was to maintain lex and Yacc... Internal DSL Constructs of a language are construed to form a DSL You don’t need to write an separate parser Commands tactfully map over to constructs like methods, etc. Also known an Embedded DSL 5
  • 6. External or Internal It depends on your application Certain languages are better suited for internal DSLs Smalltalk, Lisp, Ruby, Groovy, ... Other languages are better suited for external DSL and offer good parsing libraries or capabilities C++, Java, C#, ... 6
  • 7. Characteristics of a DSL What are some of the qualities of a DSL? Context Driven Extremely context sensitive Fluent Interfaces Provides for a humane, easy to understand interface 7
  • 8. Context Driven DSL is extremely context sensitive or context driven A lot of things are knows from the context Without context, we may be confused or misled With context, there is less clutter, terse, but readable 8
  • 9. Context Driven ... I heard my friend Neal Ford yell out Venti Latte with 2 Extra Shots What’s he talking about? He’s using the Starbucks DSL Nowhere did he mention the word coffee, but he sure got a good one at a high price ;) That’s context driven 9
  • 10. Context Driven ... I heard my friend Scott Davis mutter place a $ in a GString What’s he talking about? You don’t want to know He sure was talking about embedding variables into the Groovy’s mutable string class That’s also context driven :) 10
  • 11. Fluent Interface I was going to call this hygienic interface I like the name Eric Evans and Martin Fowler promote– Fluent Interface/Humane Interface It’s designed to be readable and to flow naturally Not easy to design–you put in more effort to create it, so it is easier for users to use 11
  • 12. A Little Compromise Command Query Separation was promoted by Bertrand Meyer Command methods—mutators or modifiers—affect object state and don’t return anything Query methods—don’t affect object state and return useful information You compromise a little to be fluent (kind of like words bent to rhyme in a poem) Command methods return self or a promoter for a good flow 12
  • 14. Fluent Interface in EasyMock 14
  • 18. Let’s Order Pizza Voice on line (VOL): Thanks for calling Joe’s You: Ya, A Large Thin Crust VOL: Toppings? You: Olives, Onions, Bell Pepper VOL: Address You: 101 Main St.,... VOL: Card? You: Visa 1234-1234-1234-1234 VOL: 20 minutes–Thank you 18
  • 19. Java Pizza Order Not fluent Very noisy—how many times do you have to say joes_pizza? Can we make it fluent? 19
  • 20. with Some languages have a with keyword within the scope, methods are invoked on an implicit object Here is an example from JavaScript 20
  • 21. with in Groovy? Groovy has no with like JavaScript But we can hack! The following does not support nested with, but you can use a stack to support it 21
  • 22. Let’s use JS to Order Pizza 22
  • 23. How about Fluent Java? Less clutter There is a context in each call Each set method (except setCard()) returns this (PizzaShop) Can we make this a bit more readable? 23
  • 24. A bit more Fluent... Method names make sense in the flow, but may not make sense alone What’s a catch? 24
  • 25. Ordered vs. Unordered Some DSLs may require a certain order in the flow You can force ordering by tactfully defining return types that will allow method chaining in only certain order Not easy Others may not require ordering It depends on the particular problem Ideally, not requiring an order is great, but may not always be possible 25
  • 26. How to Enforce Sequence? 26
  • 27. Closures Make It Easier 27
  • 28. Use A Builder Do you have to burden your class with fluent interface? Nope You may create a builder or facade that will provide a fluent interface Users can use the builder to interact instead of the underlying class 28
  • 29. Creating DSLs You may use tools like Antlr for working with DSLs JetBrains is working on Meta Programming System (MPS) Languages like Ruby and Groovy may it easier to create (internal) DSLs What makes Groovy attractive? Classes are always open Closures and Builders Categories and ExpandoMetaClass To some extent operator overloading Parenthesis are almost optional (a bit lacking) 29
  • 30. External DSLs Example Ant is a good example of an external DSL The domain here is build Ant parses your build commands Can’t exploit full capability of Java, however So, somewhat limiting or hard to extend 30
  • 31. Internal DSLs Example Pure Ruby syntax Gant similarly is pure Groovy Parsed by Ruby—no external parsing You can do as much Ruby in it as you like 31
  • 34. Creating a DSL in Groovy 34
  • 35. Using Categories Type conversions ------------------------ 2 => int .days => int .ago => Calendar .at => Date 35
  • 38. Categories vs. ExpandoMetaClass Categories allows you to tactically enhance a class ExpandoMetaClass is far reaching, global in nature You may not want to affect a class globally Categories provide controlled flexibility 38
  • 39. Quiz Time 39
  • 40. References A number of references from the following URL http://martinfowler.com/bliki/DomainSpecificLanguage.html http://docs.codehaus.org/display/GROOVY/Writing+Domain- Specific+Languages http://docs.codehaus.org/display/GROOVY/Gant http://groovy.codehaus.org/ExpandoMetaClass http://www.onboard.jetbrains.com/is1/articles/04/10/ lop/ http://www.jetbrains.com/mps 40