SlideShare a Scribd company logo
www.tothenew.com
Building DSL using
Groovy
www.tothenew.com
What is DSL?
● A computer language specialized to a particular application domain
● Not intended to be broadly applicable across domains
● Syntax is focused on intended domain or problem
● Small and simple
www.tothenew.com
About me
speaker {
name 'Puneet Behl'
organization 'TO THE NEW'
designation 'Associate Lead - Technology'
email 'puneet.behl@tothenew.com'
twitter '@puneetbhl'
github 'http://github.com/puneetbehl'
}
www.tothenew.com
Characteristics of DSL
Highly context sensitive
www.tothenew.com
Characteristics of DSL
www.tothenew.com
Characteristics of DSL
List<String> employees = ["Puneet", "Himanshu"]
employees.with {
add "Manoj"
add "Roni"
}
www.tothenew.com
Examples
take 2.pills of chloroquinine after 6.hours
www.tothenew.com
Characteristics of DSL
3.times { println “Hello” }
www.tothenew.com
Examples - Spock
class AdderSpec extends spock.lang.Specification {
def "adder-test"() {
given: "a new Adder class is created"
def adder = new Adder();
expect: "Adding two numbers to return the sum"
adder.add(3, 4) == 7
}
}
www.tothenew.com
Examples - Gradle
apply plugin: 'eclipse'
apply plugin: 'groovy'
repositories {
mavenCentral()
}
dependencies {
compile 'org.codehaus.groovy:groovy-all:2.4.10'
}
www.tothenew.com
Things to note
● Compact code
● Closer to English than programming language code
www.tothenew.com
Let’s start building DSL
www.tothenew.com
please show the square_root of 100
Using Maps
www.tothenew.com
Conference.cfp {
title "Building DSL using Groovy"
description """
Domain Specific Languages (DSLs) have become a valuable part of
the Groovy idiom. DSLs are used in native Groovy builders, Grails and
GORM, and testing frameworks. To a developer, DSLs are consumable and
understandable, which makes implementation more fluid compared to
traditional programming. But how is a DSL implemented? How does it work
behind the scenes?
In this talk, we will talk about DSL and how can we write DSL
using Groovy with various examples and see the significance of DSL
"""
level INTERMEDIATE
owner "Puneet Behl"
duration "50.mins"
}
Closure and Delegates
www.tothenew.com
candidates "John", "Alex", "Hanna"
John 7
Alex 8
Hanna 3
reportWinner
Dynamic Methods
www.tothenew.com
import groovy.time.*
Date time
use(TimeCategory) {
time = 1.week.from.now
}
println time
Categories
www.tothenew.com
String name = "JohnDoe"
String encryptedString = "23434Super secret string23434"
use(StringUtils) {
println name.camelCase
println encryptedString.removeLeadingAndTrailingToken("23434")
}
Custom Categories
www.tothenew.com
String name = "JohnDoe"
String encryptedString = "23434Super secret string23434"
use(StringUtils) {
println name.camelCase
println encryptedString.removeLeadingAndTrailingToken("23434")
}
ExpandoMetaClass
www.tothenew.com
Integrating
Groovy Script Engine
Groovy Shell
www.tothenew.com
def binding = new Binding([
robot: new Robot()
])
Using Binding
www.tothenew.com
abstract class ConferenceBaseScript extends Script {
}
Base Script Class
www.tothenew.com
import org.codehaus.groovy.control.CompilerConfiguration
// create a configuration
def config = new CompilerConfiguration()
// tweak the configuration
config.addCompilationCustomizers(...)
// run your script
def shell = new GroovyShell(config)
shell.evaluate(script)
Compiler Customization
www.tothenew.com
CompilerConfiguration config = new CompilerConfiguration()
def icz = new ImportCustomizer()
config.addCompilationCustomizers(icz)
Import Customizer
www.tothenew.com
Questions???
www.tothenew.com
References
https://github.com/puneetbehl/helloDSL
http://docs.groovy-lang.org/docs/latest/html/documentation/core-domain-specifi
c-languages.html
www.tothenew.com
Thank you

More Related Content

What's hot

Basic html5 and javascript
Basic html5 and javascriptBasic html5 and javascript
Basic html5 and javascript
wendy017
 
DomDisc and the Domino data api
DomDisc and the Domino data apiDomDisc and the Domino data api
DomDisc and the Domino data api
Jens Bruntt
 

What's hot (20)

Compact Web - Remind "web compression" -
Compact Web - Remind "web compression" -Compact Web - Remind "web compression" -
Compact Web - Remind "web compression" -
 
Understanding how concurrency work in os
Understanding how concurrency work in osUnderstanding how concurrency work in os
Understanding how concurrency work in os
 
WebGL Awesomeness
WebGL AwesomenessWebGL Awesomeness
WebGL Awesomeness
 
SPDY
SPDY SPDY
SPDY
 
Chromium OS Introduction
Chromium OS IntroductionChromium OS Introduction
Chromium OS Introduction
 
Zombilizing The Web Browser Via Flash Player 9
Zombilizing The Web Browser Via Flash Player 9Zombilizing The Web Browser Via Flash Player 9
Zombilizing The Web Browser Via Flash Player 9
 
Chromium: NaCl and Pepper API
Chromium: NaCl and Pepper APIChromium: NaCl and Pepper API
Chromium: NaCl and Pepper API
 
Basic html5 and javascript
Basic html5 and javascriptBasic html5 and javascript
Basic html5 and javascript
 
really really really awesome php application with bdd behat and iterfaces
really really really awesome php application with bdd behat and iterfacesreally really really awesome php application with bdd behat and iterfaces
really really really awesome php application with bdd behat and iterfaces
 
Node.js
Node.jsNode.js
Node.js
 
PHP client - Mongo db User Group Pune
PHP client - Mongo db User Group PunePHP client - Mongo db User Group Pune
PHP client - Mongo db User Group Pune
 
Introduction to NPM and building CLI Tools with Node.js
Introduction to NPM and building CLI Tools with Node.jsIntroduction to NPM and building CLI Tools with Node.js
Introduction to NPM and building CLI Tools with Node.js
 
Open web mail setup
Open web mail setupOpen web mail setup
Open web mail setup
 
From zero to almost rails in about a million slides...
From zero to almost rails in about a million slides...From zero to almost rails in about a million slides...
From zero to almost rails in about a million slides...
 
GWT videocall: power-up your mobile & web app with WebRTC
GWT videocall:  power-up your mobile & web app with WebRTCGWT videocall:  power-up your mobile & web app with WebRTC
GWT videocall: power-up your mobile & web app with WebRTC
 
DomDisc and the Domino data api
DomDisc and the Domino data apiDomDisc and the Domino data api
DomDisc and the Domino data api
 
Cache in Chromium: Disk Cache
Cache in Chromium: Disk CacheCache in Chromium: Disk Cache
Cache in Chromium: Disk Cache
 
Grooscript in Action SpringOne2gx 2015
Grooscript in Action SpringOne2gx 2015Grooscript in Action SpringOne2gx 2015
Grooscript in Action SpringOne2gx 2015
 
Salt and pepper — native code in the browser Browser using Google native Client
Salt and pepper — native code in the browser Browser using Google native ClientSalt and pepper — native code in the browser Browser using Google native Client
Salt and pepper — native code in the browser Browser using Google native Client
 
Grooscript greach
Grooscript greachGrooscript greach
Grooscript greach
 

Similar to Building dsl using groovy

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
 
Introducing Yeoman 1.0 beta
Introducing Yeoman 1.0 betaIntroducing Yeoman 1.0 beta
Introducing Yeoman 1.0 beta
digitalzombie
 

Similar to Building dsl using groovy (20)

Getting Started with MongoDB and Node.js
Getting Started with MongoDB and Node.jsGetting Started with MongoDB and Node.js
Getting Started with MongoDB and Node.js
 
Normalizing x pages web development
Normalizing x pages web development Normalizing x pages web development
Normalizing x pages web development
 
Desktop apps with node webkit
Desktop apps with node webkitDesktop apps with node webkit
Desktop apps with node webkit
 
Microservices in Golang
Microservices in GolangMicroservices in Golang
Microservices in Golang
 
I Just Want to Run My Code: Waypoint, Nomad, and Other Things
I Just Want to Run My Code: Waypoint, Nomad, and Other ThingsI Just Want to Run My Code: Waypoint, Nomad, and Other Things
I Just Want to Run My Code: Waypoint, Nomad, and Other Things
 
OpenNTF Webinar Series: DQL with John Curtis September 2020
OpenNTF Webinar Series: DQL with John Curtis September 2020OpenNTF Webinar Series: DQL with John Curtis September 2020
OpenNTF Webinar Series: DQL with John Curtis September 2020
 
groovy DSLs from beginner to expert
groovy DSLs from beginner to expertgroovy DSLs from beginner to expert
groovy DSLs from beginner to expert
 
PS scripting and modularization
PS scripting and modularizationPS scripting and modularization
PS scripting and modularization
 
PowerShell 8tips
PowerShell 8tipsPowerShell 8tips
PowerShell 8tips
 
DDD with Behat
DDD with BehatDDD with Behat
DDD with Behat
 
Scalable TensorFlow Deep Learning as a Service with Docker, OpenPOWER, and GPUs
Scalable TensorFlow Deep Learning as a Service with Docker, OpenPOWER, and GPUsScalable TensorFlow Deep Learning as a Service with Docker, OpenPOWER, and GPUs
Scalable TensorFlow Deep Learning as a Service with Docker, OpenPOWER, and GPUs
 
How to get started with Site Reliability Engineering
How to get started with Site Reliability EngineeringHow to get started with Site Reliability Engineering
How to get started with Site Reliability Engineering
 
TechSEO Boost 2018: Implementing Hreflang on Legacy Tech Stacks Using Service...
TechSEO Boost 2018: Implementing Hreflang on Legacy Tech Stacks Using Service...TechSEO Boost 2018: Implementing Hreflang on Legacy Tech Stacks Using Service...
TechSEO Boost 2018: Implementing Hreflang on Legacy Tech Stacks Using Service...
 
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)
 
Introduction to Go
Introduction to GoIntroduction to Go
Introduction to Go
 
DevOps Fest 2020. immutable infrastructure as code. True story.
DevOps Fest 2020. immutable infrastructure as code. True story.DevOps Fest 2020. immutable infrastructure as code. True story.
DevOps Fest 2020. immutable infrastructure as code. True story.
 
Gradle como alternativa a maven
Gradle como alternativa a mavenGradle como alternativa a maven
Gradle como alternativa a maven
 
Ed presents JSF 2.2 and WebSocket to Gameduell.
Ed presents JSF 2.2 and WebSocket to Gameduell.Ed presents JSF 2.2 and WebSocket to Gameduell.
Ed presents JSF 2.2 and WebSocket to Gameduell.
 
Introducing Yeoman 1.0 beta
Introducing Yeoman 1.0 betaIntroducing Yeoman 1.0 beta
Introducing Yeoman 1.0 beta
 
Import golang; struct microservice
Import golang; struct microserviceImport golang; struct microservice
Import golang; struct microservice
 

Recently uploaded

Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Peter Udo Diehl
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 

Recently uploaded (20)

Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxUnpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
 

Building dsl using groovy

Editor's Notes

  1. A domain-specific language (DSL) is a computer language specialized to a particular application domain. This is in contrast to a general-purpose language (GPL), which is broadly applicable across domains. There is a wide variety of DSLs, ranging from widely used languages for common domains, such as HTML for web pages, down to languages used by only one or a few pieces of software, such as Emacs Lisp for GNU Emacs and XEmacs. DSLs can be further subdivided by the kind of language, and include domain-specific markup languages, domain-specific modelinglanguages (more generally, specification languages), and domain-specific programming languages. Special-purpose computer languages have always existed in the computer age, but the term "domain-specific language" has become more popular due to the rise of domain-specific modeling. Simpler DSLs, particularly ones used by a single application, are sometimes informally called mini-languages. https://softwareengineering.stackexchange.com/questions/80389/can-css-be-considered-a-dsl
  2. We all know the English meaning of the word fart, but did you know that fartmeans speed in Danish, Norwegian, and Swedish? If that doesn’t make you snicker enough, the words for speed bump in each language are fartbump, fartshump, and farthinder.
  3. The code is written in a behaviour style, which is closer to English than to programming language code The class has clear sections annotated by labels (given: and expect:) that clearly identify the purpose of the code statements they contain Each label has a comment in the same line that provides a brief description of the business logic There are no “assert” methods (like JUnit). The code is much more compact.
  4. The code is written in a behaviour style, which is closer to English than to programming language code The class has clear sections annotated by labels (given: and expect:) that clearly identify the purpose of the code statements they contain Each label has a comment in the same line that provides a brief description of the business logic There are no “assert” methods (like JUnit). The code is much more compact.
  5. show = { println it } square_root = { Math.sqrt(it) } def please(action) { [the: { what -> [of: { n -> action(what(n)) }] }] }
  6. @TypeChecked - type checking @DelegatesTo - goal of this annotation is to solve both the documentation issue, that will let your IDE know about the expected methods in the closure body, and it will also solve the type checking issue, by giving hints to the compiler about what are the potential receivers of method calls in the closure body.
  7. The Script class provides base support for integration with your application through the Binding object, as illustrated in this example:
  8. Whether you are using groovyc to compile classes or a GroovyShell, for example, to execute scripts, under the hood, a compiler configuration is used. This configuration holds information like the source encoding or the classpath but it can also be used to perform more operations like adding imports by default, applying AST transformations transparently or disabling global AST transformations.