SlideShare uma empresa Scribd logo
1 de 38
Implementing DSLs in Groovy Matt Secoske http://blog.secosoft.net http://objectpartners.com
DSL? Groovy?
D omain  S pecific  L anguage: A language that clearly  expresses the ideas of a  particular domain
aka: fluent / humane interfaces problem oriented languages little / mini languages macros (as in Excel)
Domain Specific  Language
this:
not this:
this:
not this:
A DSL is just another tool in our toolbox.  It’s a jig to help us build our applications. picture copyrighted @2007 Pat Warner, http://www.patwarner.com
why?
bring the syntax closer to the  domain   (the experts language)
mrMustard .didIt( Murder .of( mrGreen )) .in( theKitchen ) .with( theCandleStick )
/^([a-zA-Z0-9_])+(([a-zA-Z0-9])+)+([a-zA-Z0-9]{2,4})+$/
class CreateQuizComments < ActiveRecord::Migration   def self.up   create_table :quiz_comments do |t|   t.column :name, :string   t.column :email, :string   t.column :url, :string   t.column :comment, :text    end   end   def self.down   drop_table :quiz_comments   end end
Goal:   make the  problem  easier to    understand
(My)  Ultimate  Goal:  Be able to give the code to  the experts, and have them  use  it
Types of DSLs: - Internal - External - Functional - Object Oriented
Internal DSLs  - extending a language - can be whatever  you  want - within the laws of the base    language
Groovy?
A Compelling Story: - Much of the flexibility of Ruby - Familiar Java idioms and syntax - Is focused on the JVM  - and Java “pain points”
Groovy has good DSL support:  - introspection / reflection (ability to parse(itself)) Meta-Object Protocol  - syntactic sugar Builders  Duck Typing Categories ExpandoMetaClass Named Parameters Operator Overloading
Introspection / Reflection - Access to the AST at Class loading time - Can run/load code at any time
class  MyGroovy  extends  GroovyClassLoader { protected  CompilationUnit createCompilationUnit(CompilerConfiguration config, CodeSource source) { CompilationUnit cu =  super .createCompilationUnit(config, source); cu.addPhaseOperation( new  PrimaryClassNodeOperation() { public   void   call (SourceUnit source,  GeneratorContext context,  ClassNode classNode)  throws  CompilationFailedException { String name = classNode.getName(); if  (name.endsWith( &quot;Foo&quot; )) { BlockStatement code =  new  BlockStatement(); classNode.addMethod( ”bar&quot; ,Opcodes.ACC_PUBLIC, null , null , null ,code); } } },Phases.CONVERSION); return  cu; } } Adapted from blackdrag’s blog:  http://blackdragsview.blogspot.com/2006/11/chitchat-with-groovy-compiler.html
Meta Object Protocol   - Determines what’s running at Runtime  - add/modify/intercept methods, properties MetaClass Class getFoo() doesntExistOnClass() Other Code
more Groovy syntactic sugar
Duck typing : flexible code if it walks like a duck… and it quacks like a duck… its probably a …. a =  ”a string&quot; println  a. class  // => class java.lang.String a =  1 println  a. class  // => class java.lang.Integer
builders : structured data   swing =  new  SwingBuilder() frame = swing.frame( title: 'Life'  ) {    vbox {    panel( id: 'canvas' ) {   vstrut(height: 300 )   hstrut(width: 300 )   }   hbox {   glue()    button( text: 'Next' , actionPerformed:{evolve()})    } }} frame.pack() frame.show()
Using “ use ”  (Groovy Categories) class  MeasureCategory {   static  Measurement getLbs( final  Integer self) {   new  Measurement(self, Measurement.Pounds)   } } aClosure = {->   println   4 .lbs.of( &quot;Sugar&quot; )   } use (MeasureCategory. class ) {   println   1 .lbs.of( &quot;Carrots&quot; )  // -> 1 Pounds of Carrots   aClosure. call ()   // -> 4 Pounds of Sugar }
Using  ExpandoMetaClass: metaClass =  new  ExpandoMetaClass(Integer. class , true ) metaClass.getLbs << {->   &quot;${delegate} pounds&quot; } metaClass.initialize() i =  1 ; println  i // => 1   println  i. class // => java.lang.Integer println  i.lbs // => 1 pounds
Using  ExpandoMetaClass: metaClass =  new  ExpandoMetaClass(Integer. class , true ) metaClass.getLbs << {->   &quot;${delegate} pounds&quot; } metaClass.initialize() i =  1 ; println  i // => 1   println  i. class // => java.lang.Integer println  i.lbs // => 1 pounds
To  Expando  or not to  Expando … - global usage (good and bad) - must be aware of context - naming collisions use + aspects/annotations = somewhat finer grained control
Operator Overloading: class  Foo { String meh; public  Foo(String meh) { this .meh = meh} public  String toString() { meh } public  Foo  plus (other) { new  Foo( this .meh + other.toString())   } } a =  new  Foo( &quot;Hello &quot; ) b =  new  Foo( &quot;World&quot; ) c =  &quot;New World&quot; println  a + b  // -> “Hello World” println  a + c  // -> “Hello New World”
Grails/Hibernate Criteria Builder: def  c = Account.createCriteria()  def  results = c {  like( &quot;holderFirstName&quot; ,  &quot;Fred%&quot; )  and {  between( &quot;balance&quot; ,  500 ,  1000 )  eq( &quot;branch&quot; ,  &quot;London&quot; )  }  maxResults( 10 )  order( &quot;holderLastName&quot; ,  &quot;desc&quot; )  }
A Recipe DSL: use(MeasurementCategory) { recipe =  new  Recipe() recipe.ingredients = [ 2 .cups.of( &quot;Milk&quot; ), 2 .tsps.of( &quot;Chocolate Milk Mix&quot; ) ] recipe.steps { with( &quot;drinking glass&quot; ) { add( &quot;Chocolate Milk Mix&quot; ) stirIn( &quot;Milk&quot; ) } } }
Domain Specific Language syntax approaches the problem understanding++
Three things that always matter: Naming Structure Context } Meaning
Thank You! slides at:   http://blog.secosoft.net

Mais conteúdo relacionado

Mais procurados

お題でGroovyプログラミング: Part A
お題でGroovyプログラミング: Part Aお題でGroovyプログラミング: Part A
お題でGroovyプログラミング: Part AKazuchika Sekiya
 
The JSON Architecture - BucharestJS / July
The JSON Architecture - BucharestJS / JulyThe JSON Architecture - BucharestJS / July
The JSON Architecture - BucharestJS / JulyConstantin Dumitrescu
 
C++ course start
C++ course startC++ course start
C++ course startNet3lem
 
루비가 얼랭에 빠진 날
루비가 얼랭에 빠진 날루비가 얼랭에 빠진 날
루비가 얼랭에 빠진 날Sukjoon Kim
 
Making Java Groovy (JavaOne 2013)
Making Java Groovy (JavaOne 2013)Making Java Groovy (JavaOne 2013)
Making Java Groovy (JavaOne 2013)Ken Kousen
 
大量地区化解决方案V5
大量地区化解决方案V5大量地区化解决方案V5
大量地区化解决方案V5bqconf
 
Debugging Memory Problems in Rails
Debugging Memory Problems in RailsDebugging Memory Problems in Rails
Debugging Memory Problems in RailsNasos Psarrakos
 
Replica Sets (NYC NoSQL Meetup)
Replica Sets (NYC NoSQL Meetup)Replica Sets (NYC NoSQL Meetup)
Replica Sets (NYC NoSQL Meetup)MongoDB
 
Do you Promise?
Do you Promise?Do you Promise?
Do you Promise?jungkees
 
Tokyo APAC Groundbreakers tour - The Complete Java Developer
Tokyo APAC Groundbreakers tour - The Complete Java DeveloperTokyo APAC Groundbreakers tour - The Complete Java Developer
Tokyo APAC Groundbreakers tour - The Complete Java DeveloperConnor McDonald
 
Better Software: introduction to good code
Better Software: introduction to good codeBetter Software: introduction to good code
Better Software: introduction to good codeGiordano Scalzo
 
Border Patrol - Count, throttle, kick & ban in perl
Border Patrol - Count, throttle, kick & ban in perlBorder Patrol - Count, throttle, kick & ban in perl
Border Patrol - Count, throttle, kick & ban in perlDavid Morel
 
Imutabilidade em ruby
Imutabilidade em rubyImutabilidade em ruby
Imutabilidade em rubymauricioszabo
 
GR8Conf 2009: What's New in Groovy 1.6? by Guillaume Laforge
GR8Conf 2009: What's New in Groovy 1.6? by Guillaume LaforgeGR8Conf 2009: What's New in Groovy 1.6? by Guillaume Laforge
GR8Conf 2009: What's New in Groovy 1.6? by Guillaume LaforgeGR8Conf
 

Mais procurados (20)

お題でGroovyプログラミング: Part A
お題でGroovyプログラミング: Part Aお題でGroovyプログラミング: Part A
お題でGroovyプログラミング: Part A
 
uerj201212
uerj201212uerj201212
uerj201212
 
The JSON Architecture - BucharestJS / July
The JSON Architecture - BucharestJS / JulyThe JSON Architecture - BucharestJS / July
The JSON Architecture - BucharestJS / July
 
C++ course start
C++ course startC++ course start
C++ course start
 
루비가 얼랭에 빠진 날
루비가 얼랭에 빠진 날루비가 얼랭에 빠진 날
루비가 얼랭에 빠진 날
 
Making Java Groovy (JavaOne 2013)
Making Java Groovy (JavaOne 2013)Making Java Groovy (JavaOne 2013)
Making Java Groovy (JavaOne 2013)
 
Bootstrap
BootstrapBootstrap
Bootstrap
 
Introduction kot iin
Introduction kot iinIntroduction kot iin
Introduction kot iin
 
大量地区化解决方案V5
大量地区化解决方案V5大量地区化解决方案V5
大量地区化解决方案V5
 
Debugging Memory Problems in Rails
Debugging Memory Problems in RailsDebugging Memory Problems in Rails
Debugging Memory Problems in Rails
 
Replica Sets (NYC NoSQL Meetup)
Replica Sets (NYC NoSQL Meetup)Replica Sets (NYC NoSQL Meetup)
Replica Sets (NYC NoSQL Meetup)
 
Do you Promise?
Do you Promise?Do you Promise?
Do you Promise?
 
Presentatie - Introductie in Groovy
Presentatie - Introductie in GroovyPresentatie - Introductie in Groovy
Presentatie - Introductie in Groovy
 
Tokyo APAC Groundbreakers tour - The Complete Java Developer
Tokyo APAC Groundbreakers tour - The Complete Java DeveloperTokyo APAC Groundbreakers tour - The Complete Java Developer
Tokyo APAC Groundbreakers tour - The Complete Java Developer
 
Clojure functions
Clojure functionsClojure functions
Clojure functions
 
gemdiff
gemdiffgemdiff
gemdiff
 
Better Software: introduction to good code
Better Software: introduction to good codeBetter Software: introduction to good code
Better Software: introduction to good code
 
Border Patrol - Count, throttle, kick & ban in perl
Border Patrol - Count, throttle, kick & ban in perlBorder Patrol - Count, throttle, kick & ban in perl
Border Patrol - Count, throttle, kick & ban in perl
 
Imutabilidade em ruby
Imutabilidade em rubyImutabilidade em ruby
Imutabilidade em ruby
 
GR8Conf 2009: What's New in Groovy 1.6? by Guillaume Laforge
GR8Conf 2009: What's New in Groovy 1.6? by Guillaume LaforgeGR8Conf 2009: What's New in Groovy 1.6? by Guillaume Laforge
GR8Conf 2009: What's New in Groovy 1.6? by Guillaume Laforge
 

Destaque

Building DSLs with Groovy
Building DSLs with GroovyBuilding DSLs with Groovy
Building DSLs with GroovySten Anderson
 
Groovy DSLs, from Beginner to Expert - Guillaume Laforge and Paul King - Spri...
Groovy DSLs, from Beginner to Expert - Guillaume Laforge and Paul King - Spri...Groovy DSLs, from Beginner to Expert - Guillaume Laforge and Paul King - Spri...
Groovy DSLs, from Beginner to Expert - Guillaume Laforge and Paul King - Spri...Guillaume Laforge
 
Practical Groovy Domain-Specific Languages
Practical Groovy Domain-Specific LanguagesPractical Groovy Domain-Specific Languages
Practical Groovy Domain-Specific LanguagesGuillaume Laforge
 
(Greach 2015) Dsl'ing your Groovy
(Greach 2015) Dsl'ing your Groovy(Greach 2015) Dsl'ing your Groovy
(Greach 2015) Dsl'ing your GroovyAlonso Torres
 
Going to Mars with Groovy Domain-Specific Languages
Going to Mars with Groovy Domain-Specific LanguagesGoing to Mars with Groovy Domain-Specific Languages
Going to Mars with Groovy Domain-Specific LanguagesGuillaume Laforge
 

Destaque (6)

Building DSLs with Groovy
Building DSLs with GroovyBuilding DSLs with Groovy
Building DSLs with Groovy
 
Groovy DSLs, from Beginner to Expert - Guillaume Laforge and Paul King - Spri...
Groovy DSLs, from Beginner to Expert - Guillaume Laforge and Paul King - Spri...Groovy DSLs, from Beginner to Expert - Guillaume Laforge and Paul King - Spri...
Groovy DSLs, from Beginner to Expert - Guillaume Laforge and Paul King - Spri...
 
Practical Groovy Domain-Specific Languages
Practical Groovy Domain-Specific LanguagesPractical Groovy Domain-Specific Languages
Practical Groovy Domain-Specific Languages
 
(Greach 2015) Dsl'ing your Groovy
(Greach 2015) Dsl'ing your Groovy(Greach 2015) Dsl'ing your Groovy
(Greach 2015) Dsl'ing your Groovy
 
Practical Groovy DSL
Practical Groovy DSLPractical Groovy DSL
Practical Groovy DSL
 
Going to Mars with Groovy Domain-Specific Languages
Going to Mars with Groovy Domain-Specific LanguagesGoing to Mars with Groovy Domain-Specific Languages
Going to Mars with Groovy Domain-Specific Languages
 

Semelhante a Os Secoske

ActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group PresentationActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group Presentationipolevoy
 
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...Guillaume Laforge
 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Guillaume Laforge
 
Boosting Your Testing Productivity with Groovy
Boosting Your Testing Productivity with GroovyBoosting Your Testing Productivity with Groovy
Boosting Your Testing Productivity with GroovyJames Williams
 
Javaone2008 Bof 5101 Groovytesting
Javaone2008 Bof 5101 GroovytestingJavaone2008 Bof 5101 Groovytesting
Javaone2008 Bof 5101 GroovytestingAndres Almiray
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to javaciklum_ods
 
Effecient javascript
Effecient javascriptEffecient javascript
Effecient javascriptmpnkhan
 
名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン
名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン
名古屋SGGAE/J勉強会 Grails、GaelykでハンズオンTsuyoshi Yamamoto
 
XML-Free Programming
XML-Free ProgrammingXML-Free Programming
XML-Free ProgrammingStephen Chin
 
A Recovering Java Developer Learns to Go
A Recovering Java Developer Learns to GoA Recovering Java Developer Learns to Go
A Recovering Java Developer Learns to GoMatt Stine
 
Modeling Patterns for JavaScript Browser-Based Games
Modeling Patterns for JavaScript Browser-Based GamesModeling Patterns for JavaScript Browser-Based Games
Modeling Patterns for JavaScript Browser-Based GamesRay Toal
 
The Ring programming language version 1.8 book - Part 95 of 202
The Ring programming language version 1.8 book - Part 95 of 202The Ring programming language version 1.8 book - Part 95 of 202
The Ring programming language version 1.8 book - Part 95 of 202Mahmoud Samir Fayed
 
GTAC Boosting your Testing Productivity with Groovy
GTAC Boosting your Testing Productivity with GroovyGTAC Boosting your Testing Productivity with Groovy
GTAC Boosting your Testing Productivity with GroovyAndres Almiray
 
2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Wsloffenauer
 
Groovy for Java Developers
Groovy for Java DevelopersGroovy for Java Developers
Groovy for Java DevelopersAndres Almiray
 
Groovy for java developers
Groovy for java developersGroovy for java developers
Groovy for java developersPuneet Behl
 

Semelhante a Os Secoske (20)

ActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group PresentationActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group Presentation
 
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...
 
Groovy Basics
Groovy BasicsGroovy Basics
Groovy Basics
 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008
 
Boosting Your Testing Productivity with Groovy
Boosting Your Testing Productivity with GroovyBoosting Your Testing Productivity with Groovy
Boosting Your Testing Productivity with Groovy
 
Javaone2008 Bof 5101 Groovytesting
Javaone2008 Bof 5101 GroovytestingJavaone2008 Bof 5101 Groovytesting
Javaone2008 Bof 5101 Groovytesting
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
Effecient javascript
Effecient javascriptEffecient javascript
Effecient javascript
 
名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン
名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン
名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン
 
XML-Free Programming
XML-Free ProgrammingXML-Free Programming
XML-Free Programming
 
What's New in Groovy 1.6?
What's New in Groovy 1.6?What's New in Groovy 1.6?
What's New in Groovy 1.6?
 
A Recovering Java Developer Learns to Go
A Recovering Java Developer Learns to GoA Recovering Java Developer Learns to Go
A Recovering Java Developer Learns to Go
 
Groovy
GroovyGroovy
Groovy
 
Modeling Patterns for JavaScript Browser-Based Games
Modeling Patterns for JavaScript Browser-Based GamesModeling Patterns for JavaScript Browser-Based Games
Modeling Patterns for JavaScript Browser-Based Games
 
The Ring programming language version 1.8 book - Part 95 of 202
The Ring programming language version 1.8 book - Part 95 of 202The Ring programming language version 1.8 book - Part 95 of 202
The Ring programming language version 1.8 book - Part 95 of 202
 
GTAC Boosting your Testing Productivity with Groovy
GTAC Boosting your Testing Productivity with GroovyGTAC Boosting your Testing Productivity with Groovy
GTAC Boosting your Testing Productivity with Groovy
 
2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws
 
Groovy for Java Developers
Groovy for Java DevelopersGroovy for Java Developers
Groovy for Java Developers
 
Griffon @ Svwjug
Griffon @ SvwjugGriffon @ Svwjug
Griffon @ Svwjug
 
Groovy for java developers
Groovy for java developersGroovy for java developers
Groovy for java developers
 

Mais de oscon2007

J Ruby Whirlwind Tour
J Ruby Whirlwind TourJ Ruby Whirlwind Tour
J Ruby Whirlwind Touroscon2007
 
Solr Presentation5
Solr Presentation5Solr Presentation5
Solr Presentation5oscon2007
 
Os Fitzpatrick Sussman Wiifm
Os Fitzpatrick Sussman WiifmOs Fitzpatrick Sussman Wiifm
Os Fitzpatrick Sussman Wiifmoscon2007
 
Performance Whack A Mole
Performance Whack A MolePerformance Whack A Mole
Performance Whack A Moleoscon2007
 
Os Lanphier Brashears
Os Lanphier BrashearsOs Lanphier Brashears
Os Lanphier Brashearsoscon2007
 
Os Fitzpatrick Sussman Swp
Os Fitzpatrick Sussman SwpOs Fitzpatrick Sussman Swp
Os Fitzpatrick Sussman Swposcon2007
 
Os Berlin Dispelling Myths
Os Berlin Dispelling MythsOs Berlin Dispelling Myths
Os Berlin Dispelling Mythsoscon2007
 
Os Keysholistic
Os KeysholisticOs Keysholistic
Os Keysholisticoscon2007
 
Os Jonphillips
Os JonphillipsOs Jonphillips
Os Jonphillipsoscon2007
 
Os Urnerupdated
Os UrnerupdatedOs Urnerupdated
Os Urnerupdatedoscon2007
 

Mais de oscon2007 (20)

J Ruby Whirlwind Tour
J Ruby Whirlwind TourJ Ruby Whirlwind Tour
J Ruby Whirlwind Tour
 
Solr Presentation5
Solr Presentation5Solr Presentation5
Solr Presentation5
 
Os Borger
Os BorgerOs Borger
Os Borger
 
Os Harkins
Os HarkinsOs Harkins
Os Harkins
 
Os Fitzpatrick Sussman Wiifm
Os Fitzpatrick Sussman WiifmOs Fitzpatrick Sussman Wiifm
Os Fitzpatrick Sussman Wiifm
 
Os Bunce
Os BunceOs Bunce
Os Bunce
 
Yuicss R7
Yuicss R7Yuicss R7
Yuicss R7
 
Performance Whack A Mole
Performance Whack A MolePerformance Whack A Mole
Performance Whack A Mole
 
Os Fogel
Os FogelOs Fogel
Os Fogel
 
Os Lanphier Brashears
Os Lanphier BrashearsOs Lanphier Brashears
Os Lanphier Brashears
 
Os Tucker
Os TuckerOs Tucker
Os Tucker
 
Os Fitzpatrick Sussman Swp
Os Fitzpatrick Sussman SwpOs Fitzpatrick Sussman Swp
Os Fitzpatrick Sussman Swp
 
Os Furlong
Os FurlongOs Furlong
Os Furlong
 
Os Berlin Dispelling Myths
Os Berlin Dispelling MythsOs Berlin Dispelling Myths
Os Berlin Dispelling Myths
 
Os Kimsal
Os KimsalOs Kimsal
Os Kimsal
 
Os Pruett
Os PruettOs Pruett
Os Pruett
 
Os Alrubaie
Os AlrubaieOs Alrubaie
Os Alrubaie
 
Os Keysholistic
Os KeysholisticOs Keysholistic
Os Keysholistic
 
Os Jonphillips
Os JonphillipsOs Jonphillips
Os Jonphillips
 
Os Urnerupdated
Os UrnerupdatedOs Urnerupdated
Os Urnerupdated
 

Último

Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
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 educationjfdjdjcjdnsjd
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 

Último (20)

Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
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
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 

Os Secoske

  • 1. Implementing DSLs in Groovy Matt Secoske http://blog.secosoft.net http://objectpartners.com
  • 3. D omain S pecific L anguage: A language that clearly expresses the ideas of a particular domain
  • 4. aka: fluent / humane interfaces problem oriented languages little / mini languages macros (as in Excel)
  • 5. Domain Specific Language
  • 10. A DSL is just another tool in our toolbox. It’s a jig to help us build our applications. picture copyrighted @2007 Pat Warner, http://www.patwarner.com
  • 11. why?
  • 12. bring the syntax closer to the domain (the experts language)
  • 13. mrMustard .didIt( Murder .of( mrGreen )) .in( theKitchen ) .with( theCandleStick )
  • 15. class CreateQuizComments < ActiveRecord::Migration def self.up create_table :quiz_comments do |t| t.column :name, :string t.column :email, :string t.column :url, :string t.column :comment, :text end end def self.down drop_table :quiz_comments end end
  • 16. Goal: make the problem easier to understand
  • 17. (My) Ultimate Goal: Be able to give the code to the experts, and have them use it
  • 18. Types of DSLs: - Internal - External - Functional - Object Oriented
  • 19. Internal DSLs - extending a language - can be whatever you want - within the laws of the base language
  • 21. A Compelling Story: - Much of the flexibility of Ruby - Familiar Java idioms and syntax - Is focused on the JVM - and Java “pain points”
  • 22. Groovy has good DSL support: - introspection / reflection (ability to parse(itself)) Meta-Object Protocol - syntactic sugar Builders Duck Typing Categories ExpandoMetaClass Named Parameters Operator Overloading
  • 23. Introspection / Reflection - Access to the AST at Class loading time - Can run/load code at any time
  • 24. class MyGroovy extends GroovyClassLoader { protected CompilationUnit createCompilationUnit(CompilerConfiguration config, CodeSource source) { CompilationUnit cu = super .createCompilationUnit(config, source); cu.addPhaseOperation( new PrimaryClassNodeOperation() { public void call (SourceUnit source, GeneratorContext context, ClassNode classNode) throws CompilationFailedException { String name = classNode.getName(); if (name.endsWith( &quot;Foo&quot; )) { BlockStatement code = new BlockStatement(); classNode.addMethod( ”bar&quot; ,Opcodes.ACC_PUBLIC, null , null , null ,code); } } },Phases.CONVERSION); return cu; } } Adapted from blackdrag’s blog: http://blackdragsview.blogspot.com/2006/11/chitchat-with-groovy-compiler.html
  • 25. Meta Object Protocol - Determines what’s running at Runtime - add/modify/intercept methods, properties MetaClass Class getFoo() doesntExistOnClass() Other Code
  • 27. Duck typing : flexible code if it walks like a duck… and it quacks like a duck… its probably a …. a = ”a string&quot; println a. class // => class java.lang.String a = 1 println a. class // => class java.lang.Integer
  • 28. builders : structured data swing = new SwingBuilder() frame = swing.frame( title: 'Life' ) { vbox { panel( id: 'canvas' ) { vstrut(height: 300 ) hstrut(width: 300 ) } hbox { glue() button( text: 'Next' , actionPerformed:{evolve()}) } }} frame.pack() frame.show()
  • 29. Using “ use ” (Groovy Categories) class MeasureCategory { static Measurement getLbs( final Integer self) { new Measurement(self, Measurement.Pounds) } } aClosure = {-> println 4 .lbs.of( &quot;Sugar&quot; ) } use (MeasureCategory. class ) { println 1 .lbs.of( &quot;Carrots&quot; ) // -> 1 Pounds of Carrots aClosure. call () // -> 4 Pounds of Sugar }
  • 30. Using ExpandoMetaClass: metaClass = new ExpandoMetaClass(Integer. class , true ) metaClass.getLbs << {-> &quot;${delegate} pounds&quot; } metaClass.initialize() i = 1 ; println i // => 1 println i. class // => java.lang.Integer println i.lbs // => 1 pounds
  • 31. Using ExpandoMetaClass: metaClass = new ExpandoMetaClass(Integer. class , true ) metaClass.getLbs << {-> &quot;${delegate} pounds&quot; } metaClass.initialize() i = 1 ; println i // => 1 println i. class // => java.lang.Integer println i.lbs // => 1 pounds
  • 32. To Expando or not to Expando … - global usage (good and bad) - must be aware of context - naming collisions use + aspects/annotations = somewhat finer grained control
  • 33. Operator Overloading: class Foo { String meh; public Foo(String meh) { this .meh = meh} public String toString() { meh } public Foo plus (other) { new Foo( this .meh + other.toString()) } } a = new Foo( &quot;Hello &quot; ) b = new Foo( &quot;World&quot; ) c = &quot;New World&quot; println a + b // -> “Hello World” println a + c // -> “Hello New World”
  • 34. Grails/Hibernate Criteria Builder: def c = Account.createCriteria() def results = c { like( &quot;holderFirstName&quot; , &quot;Fred%&quot; ) and { between( &quot;balance&quot; , 500 , 1000 ) eq( &quot;branch&quot; , &quot;London&quot; ) } maxResults( 10 ) order( &quot;holderLastName&quot; , &quot;desc&quot; ) }
  • 35. A Recipe DSL: use(MeasurementCategory) { recipe = new Recipe() recipe.ingredients = [ 2 .cups.of( &quot;Milk&quot; ), 2 .tsps.of( &quot;Chocolate Milk Mix&quot; ) ] recipe.steps { with( &quot;drinking glass&quot; ) { add( &quot;Chocolate Milk Mix&quot; ) stirIn( &quot;Milk&quot; ) } } }
  • 36. Domain Specific Language syntax approaches the problem understanding++
  • 37. Three things that always matter: Naming Structure Context } Meaning
  • 38. Thank You! slides at: http://blog.secosoft.net