SlideShare a Scribd company logo
ThoughtWorks



Language-Oriented Programming
and Language Workbenches:
Building Domain Languages
Atop Java™ Technology
Neal Ford
ThoughtWorker/Meme Wrangler
ThoughtWorks
www.thoughtworks.com
Session TS-1589

                  2007 JavaOneSM Conference | Session TS-1589 |
What This Session Covers
• Motivation
• Internal vs. external DSLs
• Building internal DSLs in
  • Java technology
  • Groovy
  • Ruby (via JRuby)
• Building external DSLs
• DSL best practices


                       2007 JavaOneSM Conference | Session TS-1589 |   2
Questions
• Why is there so much XML mixed in with my
  Java code?
• Why do we need things like aspects?
• Why won’t everyone shut up already about
  Ruby on Rails?
• Is there an evolutionary step beyond object-
  oriented programming?




                   2007 JavaOneSM Conference | Session TS-1589 |   3
Modeling the World With Trees




              2007 JavaOneSM Conference | Session TS-1589 |   4
Modeling the Real World




              2007 JavaOneSM Conference | Session TS-1589 |   5
Changing Abstraction Styles
• Layers of abstraction using language
   • Not trees
• Trees and hierarchies still exist
   • Underneath a stronger abstraction layer
   • Objects, aspects, generics, et al become the
     building blocks for DSLs
• Allows developers to work at a higher level
  of abstraction
• Declarative vs. imperative programming

                      2007 JavaOneSM Conference | Session TS-1589 |   6
Why Use DSLs for Abstraction?
• “Iced decaf triple grande vanilla skim with
   whip latte”
• “Scattered, smothered, covered”
   • The Waffle House Hash Brown language has 8
     keywords (all inflected verbs)
   • Scattered, smothered, covered, chunked, topped,
     diced, peppered, and capped
• “Route 66, swinging, easy on the chorus, extra
   solo at the coda, and bump at the end”
• “OMFG D00d Bob is t3h UBER 1337
   R0XX0RZ LOL”
                      2007 JavaOneSM Conference | Session TS-1589 |   7
Including Your Business
• Even if you are a Java technology ace
  • You still have to learn the DSL for your
    business on day 1
  • This is the hardest part of your job




                      2007 JavaOneSM Conference | Session TS-1589 |   8
Observation
Every non-trivial human behavior has a
domain specific language.




                    2007 JavaOneSM Conference | Session TS-1589 |   9
Nomenclature
• Coined by Martin Fowler
• Domain-specific language
  • A limited form of computer language designed for
    a specific class of problems
• Language-oriented programming
  • The general style of development which operates
    about the idea of building software around a set of
    domain specific languages




                      2007 JavaOneSM Conference | Session TS-1589 |   10
DSLs vs. APIs
• An API has an explicit context

Coffee latte = new Coffee(Size.VENTI);
latte.setFatContent(FatContent.NON_FAT);
latte.setWhip(Whip.NONE);
latte.setFoam(Foam.NONE);
latte.setTemperature(Temp.EXTRA_HOT);
latte.setStrength(5);

                   2007 JavaOneSM Conference | Session TS-1589 |   11
DSLs vs. APIs
• DSLs have an implicit context
• Consider the real-world examples
  • The context is never mentioned
  • Once a context is established, repeating it over and
    over is just noise

 Venti half-caf, non-fat, extra hot, no
 foam, no whip latte




                      2007 JavaOneSM Conference | Session TS-1589 |   12
Internal vs. External DSLs
• Internal DSLs sit atop your base language
  • Must follow the syntax rules of the base language
  • Why Groovy and Ruby make better bases
• External DSLs
  • Create a lexer and parser
  • Can take on any syntax you like
     • Let your imagination be your guide!
  • Hard to create…




                        2007 JavaOneSM Conference | Session TS-1589 |   13
Fluent Interface
• Creating a readable model
   • Convert APIs to English-like sentences
• Slightly harder to write
• Much easier to read




                      2007 JavaOneSM Conference | Session TS-1589 |   14
Car API
Car car = new CarImpl();
MarketingDescription desc = new
  MarketingDescriptionImpl();
desc.setType(quot;Boxquot;);
desc.setSubType(quot;Insulatedquot;);
desc.setAttribute(quot;lengthquot;, quot;50.5quot;);
desc.setAttribute(quot;ladderquot;, quot;yesquot;);
desc.setAttribute(quot;lining typequot;, quot;corkquot;);
car.setDescription(desc);
                 2007 JavaOneSM Conference | Session TS-1589 |   15
Car Fluent Interface
Car car = new CarImpl().withMarketingDescriptionOf(
   new MarketingDescriptionImpl(quot;Boxquot;, quot;Insulated”).
               andAttributeOf(quot;lengthquot;, quot;50.5quot;).
               andIncludesA(quot;ladderquot;).
               andAttributeOf(quot;lining typequot;, quot;corkquot;));




                       2007 JavaOneSM Conference | Session TS-1589 |   16
Existing Fluent Interfaces




              2007 JavaOneSM Conference | Session TS-1589 |   17
Fluent Interface: Hamcrest
• Hamcrest is an open source library from Google
  that creates fluent interfaces around JUnit
  matchers
 assertThat(theBiscuit, equalTo(myBiscuit));
 assertThat(theBiscuit, is(equalTo(myBiscuit)));
 assertThat(theBiscuit, is(myBiscuit));




                      2007 JavaOneSM Conference | Session TS-1589 |   18
Fluent Interface: Mocks
• JMock
 class PublisherTest extends MockObjectTestCase {
     public void testOneSubscriberReceivesAMessage() {
         Mock mockSubscriber = mock(Subscriber.class);
         Publisher publisher = new Publisher();
         publisher.add((Subscriber) mockSubscriber.proxy());
         final String message = quot;messagequot;;
         // expectations
         mockSubscriber.expects(once()).
          method(quot;receivequot;).with(eq(message));
         // execute
         publisher.publish(message);
     }
 }




                            2007 JavaOneSM Conference | Session TS-1589 |   19
Building Internal DSLs
In Java Technology




                     2007 JavaOneSM Conference | Session TS-1589 |   20
Example: Logging Configuration
• Logger setup is ugly
• Very API-ish
• Uses
  • A properties file
  • Code
  • An XML file
• Demo
  • LoggingConfiguration.java



                        2007 JavaOneSM Conference | Session TS-1589 |   21
Fluent Interface: Wrapping iBatis
• Humane interfaces improve the readability
  of any code
• You can wrap existing APIs in fluent interfaces
• Example
  •   iBatis is an open source O/R mapping tool
  •   It drips of API style of coding
  •   Wrapping iBatis access in a fluent interface
  •   Demo
       • EventPersisterImpl.java



                          2007 JavaOneSM Conference | Session TS-1589 |   22
Java Technology: A Calendar DSL
• Goal
  • Create a calendar application in Java technology
    using DSL techniques
  • Primarily uses fluent interface
  • Demo
     • Appointment.java
     • AppointmentCalendar.java
     • CalendarDemo.java




                       2007 JavaOneSM Conference | Session TS-1589 |   23
Building Internal DSLs
In Groovy




              2007 JavaOneSM Conference | Session TS-1589 |   24
Internal DSLs in Groovy
• Groovy makes a better base for DSLs
  •   Open classes via categories
  •   Closures
  •   Looser syntax rules
  •   Dynamic typing




                       2007 JavaOneSM Conference | Session TS-1589 |   25
Building Blocks: Closures
• Closures mimic scope capturing
  method pointers
• Like a method, a closure defines a scope
  • Can still reference variables from the
    enclosing scope
  • Accepts parameters
  • Allows “with” semantics with categories
• In a DSL, provides containership semantics



                     2007 JavaOneSM Conference | Session TS-1589 |   26
Building Blocks: Open Classes
• Open Classes via categories
• Groovy allows you to attach methods to an
  existing class
  • Either Groovy or Java Development Kit (JDK™)
  • Yes, you can add methods to String
• Categories are classes with static methods
  • Each method’s first parameter is self
  • Fake object-orientation
• Category demo = Adding methods to String

                      2007 JavaOneSM Conference | Session TS-1589 |   27
Time DSL in Groovy
• The goal: create a fluent interface around time
  spans and calendars
• Target syntax
 2.days.fromToday.at(4.pm)

• Returns a calendar for that date and time
• Demo
  •   IntegerWithTimeSupport.groovy
  •   CalendarDsl.groovy
  •   TestTime.groovy
  •   CalendarDslDemo.groovy
                      2007 JavaOneSM Conference | Session TS-1589 |   28
Who Returns What?
    2.days.fromToday.at(4.pm)

• 4.pm = Integer
• At
     • Accepts Integer
     • = Calendar
•     fromToday = Calendar
•     Days = Integer
•     2 = Integer

                         2007 JavaOneSM Conference | Session TS-1589 |   29
Builders in Groovy
• Builders make it much easier to build
  structures
   • XML documents
   • Swing user interfaces
• Built using a fluent interface
• Demo
   • Generating XML schema and POJO from
     a database schema



                      2007 JavaOneSM Conference | Session TS-1589 |   30
Groovy: Calendar
• The goal
  • Create an appointment calendar using DSLs
  • Demonstrates
     • Open classes
     • Closures
     • Loose syntax rules
  • Demo
     •   Appointment.groovy
     •   AppointmentCalendar.groovy
     •   IntegerWithTimeSupport.groovy
     •   AppointmentCalendarDemo.groovy


                        2007 JavaOneSM Conference | Session TS-1589 |   31
Building Internal DSLs
In Ruby




              2007 JavaOneSM Conference | Session TS-1589 |   32
Ruby
• Ruby allows you to take DSL writing
  much further
• Ruby features that enable DSLs
  • True open classes
  • Closures
  • Really flexible syntax rules




                       2007 JavaOneSM Conference | Session TS-1589 |   33
Time DSL in Ruby
• Goal
  • Support time ranges in Ruby
• Demo
  • time_dsl.rb
  • time_dsl_test.rb




                       2007 JavaOneSM Conference | Session TS-1589 |   34
Ruby Calendar
• Our calendar example in Ruby
• Demo
  • calendar_fluent.rb
• Functionally the same as the Groovy one
• Cleaner syntax
  • Less cruft
  • True open classes




                     2007 JavaOneSM Conference | Session TS-1589 |   35
Building External DSLs




             2007 JavaOneSM Conference | Session TS-1589 |   36
Language Workbenches
• A language workbench is a tool that supports
  Language oriented programming
• Today’s language workbenches
• Intentional Software (developed by Simonyi)
• Software factories (developed by Microsoft)
• Meta Programming System (developed by
  JetBrains)



                   2007 JavaOneSM Conference | Session TS-1589 |   37
Compilation Cycle (Since CS-101)




              2007 JavaOneSM Conference | Session TS-1589 |   38
“Post-IntelliJ” IDEs
• First tool that allowed you to edit against
  the abstract syntax tree instead of text
• How refactoring and other intelligent
  support works




                     2007 JavaOneSM Conference | Session TS-1589 |   39
Workbenches




              2007 JavaOneSM Conference | Session TS-1589 |   40
Language Workbenches
• Editable representation is a projection of the
  abstract representation
• Abstract representation has to be comfortable
  with errors and ambiguities




                    2007 JavaOneSM Conference | Session TS-1589 |   41
JetBrains MPS




                2007 JavaOneSM Conference | Session TS-1589 |   42
DSL Best Practices




             2007 JavaOneSM Conference | Session TS-1589 |   43
Start with the End
• When using a flexible base language,
  envision the perfect result
• The Rake napkin




                   2007 JavaOneSM Conference | Session TS-1589 |   44
Test, Test, Test!
• Writing the DSL is the tricky part
   • Using it should be easy
   • Otherwise you’ve made some mistakes
• Test all the small parts




                     2007 JavaOneSM Conference | Session TS-1589 |   45
The Problem Domain
•   Keep it as cohesive as possible
•   Don’t try to write the entire universe in your DSL
•   Better off using a bunch of very specific DSLs
•   JetBrains and the way they are using MPS




                      2007 JavaOneSM Conference | Session TS-1589 |   46
DSLs
• A huge competitive advantage
  • All your code is abstracted at the problem domain
  • Harder to write, easier to maintain
  • Show your code to your business analysts for
    verification




                     2007 JavaOneSM Conference | Session TS-1589 |   47
Questions?
Samples and slides at www.nealford.com

Neal Ford
www.nealford.com
nford@thoughtworks.com
memeagora.blogspot.com
          This work is licensed under a Creative Commons
          Attribution-ShareAlike 2.5 License:
          http://creativecommons.org/licenses/by-sa/2.5/

                          2007 JavaOneSM Conference | Session TS-1589 |

More Related Content

What's hot

Ola Bini J Ruby Power On The Jvm
Ola Bini J Ruby Power On The JvmOla Bini J Ruby Power On The Jvm
Ola Bini J Ruby Power On The Jvm
deimos
 
Ola Bini Evolving The Java Platform
Ola Bini Evolving The Java PlatformOla Bini Evolving The Java Platform
Ola Bini Evolving The Java Platform
deimos
 
Gofer 200707
Gofer 200707Gofer 200707
Gofer 200707
oscon2007
 
JSX - developing a statically-typed programming language for the Web
JSX - developing a statically-typed programming language for the WebJSX - developing a statically-typed programming language for the Web
JSX - developing a statically-typed programming language for the Web
Kazuho Oku
 

What's hot (18)

PHP Development Tools 2.0 - Success Story
PHP Development Tools 2.0 - Success StoryPHP Development Tools 2.0 - Success Story
PHP Development Tools 2.0 - Success Story
 
Ola Bini J Ruby Power On The Jvm
Ola Bini J Ruby Power On The JvmOla Bini J Ruby Power On The Jvm
Ola Bini J Ruby Power On The Jvm
 
Ola Bini Evolving The Java Platform
Ola Bini Evolving The Java PlatformOla Bini Evolving The Java Platform
Ola Bini Evolving The Java Platform
 
Gofer 200707
Gofer 200707Gofer 200707
Gofer 200707
 
Eliminating Giant VM Lock in Ruby through Hardware Transactional Memory (Ruby...
Eliminating Giant VM Lock in Ruby through Hardware Transactional Memory (Ruby...Eliminating Giant VM Lock in Ruby through Hardware Transactional Memory (Ruby...
Eliminating Giant VM Lock in Ruby through Hardware Transactional Memory (Ruby...
 
JSX
JSXJSX
JSX
 
JSX - developing a statically-typed programming language for the Web
JSX - developing a statically-typed programming language for the WebJSX - developing a statically-typed programming language for the Web
JSX - developing a statically-typed programming language for the Web
 
GraalVM - MadridJUG 2019-10-22
GraalVM - MadridJUG 2019-10-22GraalVM - MadridJUG 2019-10-22
GraalVM - MadridJUG 2019-10-22
 
Rcs project Training Bangalore
Rcs project Training BangaloreRcs project Training Bangalore
Rcs project Training Bangalore
 
re7olabini
re7olabinire7olabini
re7olabini
 
Kamaelia - Networking Using Generators
Kamaelia - Networking Using GeneratorsKamaelia - Networking Using Generators
Kamaelia - Networking Using Generators
 
JSX Optimizer
JSX OptimizerJSX Optimizer
JSX Optimizer
 
Tiery Eyed
Tiery EyedTiery Eyed
Tiery Eyed
 
Launchpad: Lessons Learnt
Launchpad: Lessons LearntLaunchpad: Lessons Learnt
Launchpad: Lessons Learnt
 
#JavaOne What's in an object?
#JavaOne What's in an object?#JavaOne What's in an object?
#JavaOne What's in an object?
 
GraalVM - OpenSlava 2019-10-18
GraalVM - OpenSlava 2019-10-18GraalVM - OpenSlava 2019-10-18
GraalVM - OpenSlava 2019-10-18
 
Zend Server: A Guided Tour
Zend Server: A Guided TourZend Server: A Guided Tour
Zend Server: A Guided Tour
 
GraalVM - JBCNConf 2019-05-28
GraalVM - JBCNConf 2019-05-28GraalVM - JBCNConf 2019-05-28
GraalVM - JBCNConf 2019-05-28
 

Similar to Language-Oriented Programming and Language Workbenches: Building Domain Languages Atop Java Technology

JRuby - Enterprise 2.0
JRuby - Enterprise 2.0JRuby - Enterprise 2.0
JRuby - Enterprise 2.0
Jan Sifra
 
Laird Best Practices Ajax World West2008
Laird Best Practices Ajax World West2008Laird Best Practices Ajax World West2008
Laird Best Practices Ajax World West2008
rajivmordani
 
Buildingwebapplicationswith.net
Buildingwebapplicationswith.netBuildingwebapplicationswith.net
Buildingwebapplicationswith.net
Kolagani Veera
 
Writing Your Own JSR-Compliant, Domain-Specific Scripting Language
Writing Your Own JSR-Compliant, Domain-Specific Scripting LanguageWriting Your Own JSR-Compliant, Domain-Specific Scripting Language
Writing Your Own JSR-Compliant, Domain-Specific Scripting Language
elliando dias
 
An Infrastructure for Team Development - Gaylord Aulke
An Infrastructure for Team Development - Gaylord AulkeAn Infrastructure for Team Development - Gaylord Aulke
An Infrastructure for Team Development - Gaylord Aulke
dpc
 
Nuxeo JavaOne 2007 presentation (in original format)
Nuxeo JavaOne 2007 presentation (in original format)Nuxeo JavaOne 2007 presentation (in original format)
Nuxeo JavaOne 2007 presentation (in original format)
Stefane Fermigier
 
Javascript Framework Roundup FYB
Javascript Framework Roundup FYBJavascript Framework Roundup FYB
Javascript Framework Roundup FYB
nukeevry1
 
Ajax Tutorial
Ajax TutorialAjax Tutorial
Ajax Tutorial
oscon2007
 
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
 
Kann JavaScript elegant sein?
Kann JavaScript elegant sein?Kann JavaScript elegant sein?
Kann JavaScript elegant sein?
jbandi
 

Similar to Language-Oriented Programming and Language Workbenches: Building Domain Languages Atop Java Technology (20)

JRuby - Enterprise 2.0
JRuby - Enterprise 2.0JRuby - Enterprise 2.0
JRuby - Enterprise 2.0
 
Laird Best Practices Ajax World West2008
Laird Best Practices Ajax World West2008Laird Best Practices Ajax World West2008
Laird Best Practices Ajax World West2008
 
HOW TO CREATE AWESOME POLYGLOT APPLICATIONS USING GRAALVM
HOW TO CREATE AWESOME POLYGLOT APPLICATIONS USING GRAALVMHOW TO CREATE AWESOME POLYGLOT APPLICATIONS USING GRAALVM
HOW TO CREATE AWESOME POLYGLOT APPLICATIONS USING GRAALVM
 
Buildingwebapplicationswith.net
Buildingwebapplicationswith.netBuildingwebapplicationswith.net
Buildingwebapplicationswith.net
 
Symfony for non-techies
Symfony for non-techiesSymfony for non-techies
Symfony for non-techies
 
Persistent Memory Programming with Pmemkv
Persistent Memory Programming with PmemkvPersistent Memory Programming with Pmemkv
Persistent Memory Programming with Pmemkv
 
Practical Groovy DSL
Practical Groovy DSLPractical Groovy DSL
Practical Groovy DSL
 
Writing Your Own JSR-Compliant, Domain-Specific Scripting Language
Writing Your Own JSR-Compliant, Domain-Specific Scripting LanguageWriting Your Own JSR-Compliant, Domain-Specific Scripting Language
Writing Your Own JSR-Compliant, Domain-Specific Scripting Language
 
Road to sbt 1.0 paved with server
Road to sbt 1.0   paved with serverRoad to sbt 1.0   paved with server
Road to sbt 1.0 paved with server
 
An Infrastructure for Team Development - Gaylord Aulke
An Infrastructure for Team Development - Gaylord AulkeAn Infrastructure for Team Development - Gaylord Aulke
An Infrastructure for Team Development - Gaylord Aulke
 
How and Why GraalVM is quickly becoming relevant for developers (ACEs@home - ...
How and Why GraalVM is quickly becoming relevant for developers (ACEs@home - ...How and Why GraalVM is quickly becoming relevant for developers (ACEs@home - ...
How and Why GraalVM is quickly becoming relevant for developers (ACEs@home - ...
 
Nuxeo JavaOne 2007 presentation (in original format)
Nuxeo JavaOne 2007 presentation (in original format)Nuxeo JavaOne 2007 presentation (in original format)
Nuxeo JavaOne 2007 presentation (in original format)
 
Road to sbt 1.0: Paved with server (2015 Amsterdam)
Road to sbt 1.0: Paved with server (2015 Amsterdam)Road to sbt 1.0: Paved with server (2015 Amsterdam)
Road to sbt 1.0: Paved with server (2015 Amsterdam)
 
Javascript Framework Roundup FYB
Javascript Framework Roundup FYBJavascript Framework Roundup FYB
Javascript Framework Roundup FYB
 
Ajax Tutorial
Ajax TutorialAjax Tutorial
Ajax Tutorial
 
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)
 
Real World Technologies
Real World TechnologiesReal World Technologies
Real World Technologies
 
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory Course
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory CourseRuby on Rails 101 - Presentation Slides for a Five Day Introductory Course
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory Course
 
Alessandro Salvatico - Sviluppare J2EE con INGRES
Alessandro Salvatico - Sviluppare J2EE con INGRESAlessandro Salvatico - Sviluppare J2EE con INGRES
Alessandro Salvatico - Sviluppare J2EE con INGRES
 
Kann JavaScript elegant sein?
Kann JavaScript elegant sein?Kann JavaScript elegant sein?
Kann JavaScript elegant sein?
 

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

Recently uploaded (20)

SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
 
Speed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in MinutesSpeed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in Minutes
 
IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024
 
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdfLinux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
 
Agentic RAG What it is its types applications and implementation.pdf
Agentic RAG What it is its types applications and implementation.pdfAgentic RAG What it is its types applications and implementation.pdf
Agentic RAG What it is its types applications and implementation.pdf
 
WSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptxWSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptx
 
The Metaverse: Are We There Yet?
The  Metaverse:    Are   We  There  Yet?The  Metaverse:    Are   We  There  Yet?
The Metaverse: Are We There Yet?
 
10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka Doktorová10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka Doktorová
 
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
 
Top 10 Symfony Development Companies 2024
Top 10 Symfony Development Companies 2024Top 10 Symfony Development Companies 2024
Top 10 Symfony Development Companies 2024
 
Buy Epson EcoTank L3210 Colour Printer Online.pdf
Buy Epson EcoTank L3210 Colour Printer Online.pdfBuy Epson EcoTank L3210 Colour Printer Online.pdf
Buy Epson EcoTank L3210 Colour Printer Online.pdf
 
Designing for Hardware Accessibility at Comcast
Designing for Hardware Accessibility at ComcastDesigning for Hardware Accessibility at Comcast
Designing for Hardware Accessibility at Comcast
 
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
 
Salesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone KomSalesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
 
Syngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdfSyngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdf
 
AI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří KarpíšekAI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří Karpíšek
 
What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024
 
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdfSimplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
 
Introduction to Open Source RAG and RAG Evaluation
Introduction to Open Source RAG and RAG EvaluationIntroduction to Open Source RAG and RAG Evaluation
Introduction to Open Source RAG and RAG Evaluation
 
ECS 2024 Teams Premium - Pretty Secure
ECS 2024   Teams Premium - Pretty SecureECS 2024   Teams Premium - Pretty Secure
ECS 2024 Teams Premium - Pretty Secure
 

Language-Oriented Programming and Language Workbenches: Building Domain Languages Atop Java Technology

  • 1. ThoughtWorks Language-Oriented Programming and Language Workbenches: Building Domain Languages Atop Java™ Technology Neal Ford ThoughtWorker/Meme Wrangler ThoughtWorks www.thoughtworks.com Session TS-1589 2007 JavaOneSM Conference | Session TS-1589 |
  • 2. What This Session Covers • Motivation • Internal vs. external DSLs • Building internal DSLs in • Java technology • Groovy • Ruby (via JRuby) • Building external DSLs • DSL best practices 2007 JavaOneSM Conference | Session TS-1589 | 2
  • 3. Questions • Why is there so much XML mixed in with my Java code? • Why do we need things like aspects? • Why won’t everyone shut up already about Ruby on Rails? • Is there an evolutionary step beyond object- oriented programming? 2007 JavaOneSM Conference | Session TS-1589 | 3
  • 4. Modeling the World With Trees 2007 JavaOneSM Conference | Session TS-1589 | 4
  • 5. Modeling the Real World 2007 JavaOneSM Conference | Session TS-1589 | 5
  • 6. Changing Abstraction Styles • Layers of abstraction using language • Not trees • Trees and hierarchies still exist • Underneath a stronger abstraction layer • Objects, aspects, generics, et al become the building blocks for DSLs • Allows developers to work at a higher level of abstraction • Declarative vs. imperative programming 2007 JavaOneSM Conference | Session TS-1589 | 6
  • 7. Why Use DSLs for Abstraction? • “Iced decaf triple grande vanilla skim with whip latte” • “Scattered, smothered, covered” • The Waffle House Hash Brown language has 8 keywords (all inflected verbs) • Scattered, smothered, covered, chunked, topped, diced, peppered, and capped • “Route 66, swinging, easy on the chorus, extra solo at the coda, and bump at the end” • “OMFG D00d Bob is t3h UBER 1337 R0XX0RZ LOL” 2007 JavaOneSM Conference | Session TS-1589 | 7
  • 8. Including Your Business • Even if you are a Java technology ace • You still have to learn the DSL for your business on day 1 • This is the hardest part of your job 2007 JavaOneSM Conference | Session TS-1589 | 8
  • 9. Observation Every non-trivial human behavior has a domain specific language. 2007 JavaOneSM Conference | Session TS-1589 | 9
  • 10. Nomenclature • Coined by Martin Fowler • Domain-specific language • A limited form of computer language designed for a specific class of problems • Language-oriented programming • The general style of development which operates about the idea of building software around a set of domain specific languages 2007 JavaOneSM Conference | Session TS-1589 | 10
  • 11. DSLs vs. APIs • An API has an explicit context Coffee latte = new Coffee(Size.VENTI); latte.setFatContent(FatContent.NON_FAT); latte.setWhip(Whip.NONE); latte.setFoam(Foam.NONE); latte.setTemperature(Temp.EXTRA_HOT); latte.setStrength(5); 2007 JavaOneSM Conference | Session TS-1589 | 11
  • 12. DSLs vs. APIs • DSLs have an implicit context • Consider the real-world examples • The context is never mentioned • Once a context is established, repeating it over and over is just noise Venti half-caf, non-fat, extra hot, no foam, no whip latte 2007 JavaOneSM Conference | Session TS-1589 | 12
  • 13. Internal vs. External DSLs • Internal DSLs sit atop your base language • Must follow the syntax rules of the base language • Why Groovy and Ruby make better bases • External DSLs • Create a lexer and parser • Can take on any syntax you like • Let your imagination be your guide! • Hard to create… 2007 JavaOneSM Conference | Session TS-1589 | 13
  • 14. Fluent Interface • Creating a readable model • Convert APIs to English-like sentences • Slightly harder to write • Much easier to read 2007 JavaOneSM Conference | Session TS-1589 | 14
  • 15. Car API Car car = new CarImpl(); MarketingDescription desc = new MarketingDescriptionImpl(); desc.setType(quot;Boxquot;); desc.setSubType(quot;Insulatedquot;); desc.setAttribute(quot;lengthquot;, quot;50.5quot;); desc.setAttribute(quot;ladderquot;, quot;yesquot;); desc.setAttribute(quot;lining typequot;, quot;corkquot;); car.setDescription(desc); 2007 JavaOneSM Conference | Session TS-1589 | 15
  • 16. Car Fluent Interface Car car = new CarImpl().withMarketingDescriptionOf( new MarketingDescriptionImpl(quot;Boxquot;, quot;Insulated”). andAttributeOf(quot;lengthquot;, quot;50.5quot;). andIncludesA(quot;ladderquot;). andAttributeOf(quot;lining typequot;, quot;corkquot;)); 2007 JavaOneSM Conference | Session TS-1589 | 16
  • 17. Existing Fluent Interfaces 2007 JavaOneSM Conference | Session TS-1589 | 17
  • 18. Fluent Interface: Hamcrest • Hamcrest is an open source library from Google that creates fluent interfaces around JUnit matchers assertThat(theBiscuit, equalTo(myBiscuit)); assertThat(theBiscuit, is(equalTo(myBiscuit))); assertThat(theBiscuit, is(myBiscuit)); 2007 JavaOneSM Conference | Session TS-1589 | 18
  • 19. Fluent Interface: Mocks • JMock class PublisherTest extends MockObjectTestCase { public void testOneSubscriberReceivesAMessage() { Mock mockSubscriber = mock(Subscriber.class); Publisher publisher = new Publisher(); publisher.add((Subscriber) mockSubscriber.proxy()); final String message = quot;messagequot;; // expectations mockSubscriber.expects(once()). method(quot;receivequot;).with(eq(message)); // execute publisher.publish(message); } } 2007 JavaOneSM Conference | Session TS-1589 | 19
  • 20. Building Internal DSLs In Java Technology 2007 JavaOneSM Conference | Session TS-1589 | 20
  • 21. Example: Logging Configuration • Logger setup is ugly • Very API-ish • Uses • A properties file • Code • An XML file • Demo • LoggingConfiguration.java 2007 JavaOneSM Conference | Session TS-1589 | 21
  • 22. Fluent Interface: Wrapping iBatis • Humane interfaces improve the readability of any code • You can wrap existing APIs in fluent interfaces • Example • iBatis is an open source O/R mapping tool • It drips of API style of coding • Wrapping iBatis access in a fluent interface • Demo • EventPersisterImpl.java 2007 JavaOneSM Conference | Session TS-1589 | 22
  • 23. Java Technology: A Calendar DSL • Goal • Create a calendar application in Java technology using DSL techniques • Primarily uses fluent interface • Demo • Appointment.java • AppointmentCalendar.java • CalendarDemo.java 2007 JavaOneSM Conference | Session TS-1589 | 23
  • 24. Building Internal DSLs In Groovy 2007 JavaOneSM Conference | Session TS-1589 | 24
  • 25. Internal DSLs in Groovy • Groovy makes a better base for DSLs • Open classes via categories • Closures • Looser syntax rules • Dynamic typing 2007 JavaOneSM Conference | Session TS-1589 | 25
  • 26. Building Blocks: Closures • Closures mimic scope capturing method pointers • Like a method, a closure defines a scope • Can still reference variables from the enclosing scope • Accepts parameters • Allows “with” semantics with categories • In a DSL, provides containership semantics 2007 JavaOneSM Conference | Session TS-1589 | 26
  • 27. Building Blocks: Open Classes • Open Classes via categories • Groovy allows you to attach methods to an existing class • Either Groovy or Java Development Kit (JDK™) • Yes, you can add methods to String • Categories are classes with static methods • Each method’s first parameter is self • Fake object-orientation • Category demo = Adding methods to String 2007 JavaOneSM Conference | Session TS-1589 | 27
  • 28. Time DSL in Groovy • The goal: create a fluent interface around time spans and calendars • Target syntax 2.days.fromToday.at(4.pm) • Returns a calendar for that date and time • Demo • IntegerWithTimeSupport.groovy • CalendarDsl.groovy • TestTime.groovy • CalendarDslDemo.groovy 2007 JavaOneSM Conference | Session TS-1589 | 28
  • 29. Who Returns What? 2.days.fromToday.at(4.pm) • 4.pm = Integer • At • Accepts Integer • = Calendar • fromToday = Calendar • Days = Integer • 2 = Integer 2007 JavaOneSM Conference | Session TS-1589 | 29
  • 30. Builders in Groovy • Builders make it much easier to build structures • XML documents • Swing user interfaces • Built using a fluent interface • Demo • Generating XML schema and POJO from a database schema 2007 JavaOneSM Conference | Session TS-1589 | 30
  • 31. Groovy: Calendar • The goal • Create an appointment calendar using DSLs • Demonstrates • Open classes • Closures • Loose syntax rules • Demo • Appointment.groovy • AppointmentCalendar.groovy • IntegerWithTimeSupport.groovy • AppointmentCalendarDemo.groovy 2007 JavaOneSM Conference | Session TS-1589 | 31
  • 32. Building Internal DSLs In Ruby 2007 JavaOneSM Conference | Session TS-1589 | 32
  • 33. Ruby • Ruby allows you to take DSL writing much further • Ruby features that enable DSLs • True open classes • Closures • Really flexible syntax rules 2007 JavaOneSM Conference | Session TS-1589 | 33
  • 34. Time DSL in Ruby • Goal • Support time ranges in Ruby • Demo • time_dsl.rb • time_dsl_test.rb 2007 JavaOneSM Conference | Session TS-1589 | 34
  • 35. Ruby Calendar • Our calendar example in Ruby • Demo • calendar_fluent.rb • Functionally the same as the Groovy one • Cleaner syntax • Less cruft • True open classes 2007 JavaOneSM Conference | Session TS-1589 | 35
  • 36. Building External DSLs 2007 JavaOneSM Conference | Session TS-1589 | 36
  • 37. Language Workbenches • A language workbench is a tool that supports Language oriented programming • Today’s language workbenches • Intentional Software (developed by Simonyi) • Software factories (developed by Microsoft) • Meta Programming System (developed by JetBrains) 2007 JavaOneSM Conference | Session TS-1589 | 37
  • 38. Compilation Cycle (Since CS-101) 2007 JavaOneSM Conference | Session TS-1589 | 38
  • 39. “Post-IntelliJ” IDEs • First tool that allowed you to edit against the abstract syntax tree instead of text • How refactoring and other intelligent support works 2007 JavaOneSM Conference | Session TS-1589 | 39
  • 40. Workbenches 2007 JavaOneSM Conference | Session TS-1589 | 40
  • 41. Language Workbenches • Editable representation is a projection of the abstract representation • Abstract representation has to be comfortable with errors and ambiguities 2007 JavaOneSM Conference | Session TS-1589 | 41
  • 42. JetBrains MPS 2007 JavaOneSM Conference | Session TS-1589 | 42
  • 43. DSL Best Practices 2007 JavaOneSM Conference | Session TS-1589 | 43
  • 44. Start with the End • When using a flexible base language, envision the perfect result • The Rake napkin 2007 JavaOneSM Conference | Session TS-1589 | 44
  • 45. Test, Test, Test! • Writing the DSL is the tricky part • Using it should be easy • Otherwise you’ve made some mistakes • Test all the small parts 2007 JavaOneSM Conference | Session TS-1589 | 45
  • 46. The Problem Domain • Keep it as cohesive as possible • Don’t try to write the entire universe in your DSL • Better off using a bunch of very specific DSLs • JetBrains and the way they are using MPS 2007 JavaOneSM Conference | Session TS-1589 | 46
  • 47. DSLs • A huge competitive advantage • All your code is abstracted at the problem domain • Harder to write, easier to maintain • Show your code to your business analysts for verification 2007 JavaOneSM Conference | Session TS-1589 | 47
  • 48. Questions? Samples and slides at www.nealford.com Neal Ford www.nealford.com nford@thoughtworks.com memeagora.blogspot.com This work is licensed under a Creative Commons Attribution-ShareAlike 2.5 License: http://creativecommons.org/licenses/by-sa/2.5/ 2007 JavaOneSM Conference | Session TS-1589 |