SlideShare a Scribd company logo
Groovy
Metaprogramming
for Dummies
Darren Cruse
(not a professional speaker: please no heckling or throwing of food
per Groovy User Group Regulation 103a subsection e)
Monday, June 7, 2010
Meta Stuff
(about the meta talk)
•Who am I?
Once too good for “scripting”
Former Perl Nut
Recent Javascript Graduate
Improving Groovy Skills
Monday, June 7, 2010
Meta Stuff
(about the meta talk)
•What’s this talk about?
metaprogramming = “programming the
program”
metaprogramming = what makes groovy
really groovy!
Monday, June 7, 2010
Meta Stuff
(about the meta talk)
• Who’s this talk for?
Ideally: Someone who’s seen a bit of groovy and aspires to get
to the next level
Someone still unconvinced groovy’s power and productivity is
sufficiently greater than java’s to merit learning a language
with such a silly name.
(and you advanced guys feel free to dive in and help me out!)
Monday, June 7, 2010
Builders = Metaprogramming Magic
def builder = new StreamingMarkupBuilder()
builder.encoding = 'UTF-8'
def books = builder.bind {
mkp.xmlDeclaration()
namespaces << [meta:'http://meta/book/info']
books(count: 3) {
book(id: 1) {
title lang:'en', 'Groovy in Action'
meta.isbn '1-932394-84-2'
}
book(id: 2) {
title lang:'en', 'Groovy Programming'
meta.isbn '0123725070'
}
book(id: 3) {
title 'Groovy & Grails'
comment << 'Not yet available.'
}
book(id: 4) {
mkp.yieldUnescaped '<title>Griffon Guide</title>'
}
}
}
Monday, June 7, 2010
Builders = Metaprogramming Magic
<?xml version="1.0" encoding="UTF-8"?>
<books xmlns:meta="http://meta/book/info" count="3">
<book id="1">
<title lang="en">Groovy in Action</title>
<meta:isbn>1-932394-84-2</meta:isbn>
</book>
<book id="2">
<title lang="en">Groovy Programming</title>
<meta:isbn>0123725070</meta:isbn>
</book>
<book id="3">
<title>Groovy &amp; Grails</title>
<!--Not yet available.-->
</book>
<book id="4">
<title>Griffon Guide</title>
</book>
</books>
Monday, June 7, 2010
def builder = new StreamingMarkupBuilder()
builder.encoding = 'UTF-8'
def books = builder.bind {
mkp.xmlDeclaration()
namespaces << [meta:'http://meta/book/info']
books(count: 3) {
book(id: 1) {
title lang:'en', 'Groovy in Action'
meta.isbn '1-932394-84-2'
}
book(id: 2) {
title lang:'en', 'Groovy Programming'
meta.isbn '0123725070'
}
book(id: 3) {
title 'Groovy & Grails'
comment << 'Not yet available.'
}
book(id: 4) {
mkp.yieldUnescaped '<title>Griffon Guide</title>'
}
}
}
println XmlUtil.serialize(books)
Builders = Metaprogramming Magic
<?xml version="1.0" encoding="UTF-8"?>
<books xmlns:meta="http://meta/book/info" count="3">
<book id="1">
<title lang="en">Groovy in Action</title>
<meta:isbn>1-932394-84-2</meta:isbn>
</book>
<book id="2">
<title lang="en">Groovy Programming</title>
<meta:isbn>0123725070</meta:isbn>
</book>
<book id="3">
<title>Groovy &amp; Grails</title>
<!--Not yet available.-->
</book>
<book id="4">
<title>Griffon Guide</title>
</book>
</books>
Monday, June 7, 2010
book(id: 2) {
title lang:'en', 'Groovy Programming'
meta.isbn '0123725070'
}
XML Builders = An alternative
Syntax for XML
<book id="2">
<title lang="en">Groovy Programming</title>
<meta:isbn>0123725070</meta:isbn>
</book>
Monday, June 7, 2010
But How?
(is it code or is it data?)
Any sufficiently advanced
technology is
indistinguishable from
magic.
Arthur C. Clarke,
English physicist & science fiction author (1917 - )
def builder = new StreamingMarkupBuilder()
builder.encoding = 'UTF-8'
def books = builder.bind {
mkp.xmlDeclaration()
namespaces << [meta:'http://meta/book/info']
books(count: 3) {
book(id: 1) {
title lang:'en', 'Groovy in Action'
meta.isbn '1-932394-84-2'
}
book(id: 2) {
title lang:'en', 'Groovy Programming'
meta.isbn '0123725070'
}
book(id: 3) {
title 'Groovy & Grails' // & is converted to &amp;
comment << 'Not yet available.'
}
book(id: 4) {
mkp.yieldUnescaped '<title>Griffon Guide</title>'
}
}
}
println XmlUtil.serialize(books)
Monday, June 7, 2010
The Answer Lies in Groovy’s Nature As a
Dynamic Language
(as distinguished from java)
compile
time
Java
run
time
compile
time
Groovy
run
time
Monday, June 7, 2010
Java Compilation
java
source
byte
code
Monday, June 7, 2010
Groovy Compilation
groovy
source
byte
code
meta
program
Monday, June 7, 2010
The Program Generated...
Evaluates Your Program At Runtime...
...it does so using a framework that is
designed for you to plug into...
When you do so you are “programming
the program”...
i.e. metaprogramming.
Monday, June 7, 2010
This framework is called
the “Meta Object Protocol”
(“protocol” in the sense of an “api”)
MOPMonday, June 7, 2010
If you’re familiar with a
framework like Struts...
This really isn’t that different:
Instead of mapping url requests to the code that handles them, you’re
mapping actual method calls and property accesses to the code that
handles them!
Instead of using struts-config.xml to do the mapping, you’re using
actual code in the form of data structures called “meta classes”
The simplest and coolest of these is called the
ExpandoMetaClass!
Monday, June 7, 2010
All Groovy Objects Implement...
public interface GroovyObject {
Object invokeMethod(String name, Object args);
Object getProperty(String propertyName);
void setProperty(String propertyName, Object newValue);
MetaClass getMetaClass();
void setMetaClass(MetaClass metaClass);
}
(This the heartbeat of the MOP)
Monday, June 7, 2010
MetaClasses Implement these methods for a class
and thereby define the behavior of the class.
Object invokeMethod(String name, Object args);
Object getProperty(String propertyName);
void setProperty(String propertyName, Object newValue);
The beauty of ExpandoMetaClass is that you can add
methods and properties to classes simply by assigning
them - it expands indefinitely (like a Map).
Monday, June 7, 2010
So The Magic Is Revealed
(dynamic dispatch and missing methods)
<?xml version="1.0" encoding="UTF-8"?>
<books xmlns:meta="http://meta/book/info" count="3">
<book id="1">
<title lang="en">Groovy in Action</title>
<meta:isbn>1-932394-84-2</meta:isbn>
</book>
<book id="2">
<title lang="en">Groovy Programming</title>
<meta:isbn>0123725070</meta:isbn>
</book>
<book id="3">
<title>Groovy &amp; Grails</title>
<!--Not yet available.-->
</book>
<book id="4">
<title>Griffon Guide</title>
</book>
</books>
def builder = new StreamingMarkupBuilder()
builder.encoding = 'UTF-8'
def books = builder.bind {
mkp.xmlDeclaration()
namespaces << [meta:'http://meta/book/info']
books(count: 3) {
book(id: 1) {
title lang:'en', 'Groovy in Action'
meta.isbn '1-932394-84-2'
}
book(id: 2) {
title lang:'en', 'Groovy Programming'
meta.isbn '0123725070'
}
book(id: 3) {
title 'Groovy & Grails' // & is converted to &amp;
comment << 'Not yet available.'
}
book(id: 4) {
mkp.yieldUnescaped '<title>Griffon Guide</title>'
}
}
}
println XmlUtil.serialize(books)
Monday, June 7, 2010
When it comes to Groovy’s syntax...
What you can write is fixed by the
parser (like most languages)...
but there’s lots of optional stuff
optional “()“, optional “;”,
optional “[]” (sometimes)...
so much optional it sounds nuts!
but there’s a method to the
madness.
Monday, June 7, 2010
Combining the MOP with Groovy’s loose syntax...
You can highjack the meaning
behind what the evaluator thinks
are method or property calls
but which supericially look more
“declarative” than imperative
more “what” than “how”
the result can be shorter and
clearer than java
Monday, June 7, 2010
Grails uses this stuff a lot...
It has a lot of these “domain specific languages” or
“DSL”s
but this talk is about groovy it’s not about grails
But grails is the best example of where these approaches
are used all over the place to do amazing things with just a
little code...
so this talk is about grails
DSL
But it’s not
it’s about how grails does things under the covers
about how *groovy* does things under the covers
so this is a meta talk about grails
Exactly (exact-o-mundo)
Monday, June 7, 2010
And DSLs aren’t the only thing
The combination of closures and metaclasses
can allow much coolness including:
AOP
IOC
Memoization
RMI via REST
(well, at least the factory pattern)
(a fancy word for caching)
(how many acronyms you gonna use?)
(without the AOP)
(coolness = productivity)
Monday, June 7, 2010
The preceding will be demonstrated with some
delightful code examples.
But first...
Monday, June 7, 2010
A Review of Closures for Newbies...
A java assignment:
int val = 3;
A java function:
public int func(int a, int b) {
return a + b;
}
Or in Groovy:
def val = 3
A groovy function:
def func(a, b) {
a + b
}
Monday, June 7, 2010
A Review of Closures for Newbies...
def func = (a, b) {
a + b
}
Closures are anonymous functions that can be assigned
as *values*...
From the previously slide you can *almost* guess the syntax:
Close! Above itʼs the variable that holds the name so itʼs on
the left thatʼs correct. The wrong part is the parameters:
def func = { a, b ->
a + b
}
Groovyʼs syntax is nice because the “{“ and “}” clearly mark the “code block”.
Monday, June 7, 2010
A Review of Closures for Newbies...
def class Counter {
int count
def increment = { count ++ }
}
One more thing about closures - regarding scoping...
A closure defined in the lexical scope of other code can refer
to itʼs variables. This surrounding code is the “owner”:
But when closures are assigned to other objects, thereʼs more to
life than just the surrounding code - esp. note the delegate:
this: as in Java, this refers to the instance of the enclosing
class where a Closure is defined
owner : the enclosing object (this or a surrounding Closure)
delegate : by default the same as owner, but changeable for
example in a builder or ExpandoMetaClass
Monday, June 7, 2010
A Review of Closures for Newbies...
def postiveOnly(Closure c) {
list.each { val ->
if(val > 0)
c.call(val)
}
}
Oh! And one more thing about closures...
Groovy has syntactic sugar which allows a function taking a
closure as itʼs final argument can be called with the closure
passed after the functions closing paren:
Can be called like so:
postiveOnly { val -> println “$val is > 0” }
And lastly: the default parameter if none is specified is simply “it”:
postiveOnly { println “$it is > 0” }
Monday, June 7, 2010
Finally: some real metaprogramming...
String.metaClass.shout = { delegate.toUpperCase(); }
println "Groovy".shout()
Add a method to a class:
And yes, you could even:
(but just because you can doesnʼt mean you will)
This just shows what a flexible and powerful language groovy is.
postiveOnly { println “$it is > 0” }
String.metaClass.toUpperCase = { delegate.toLowerCase(); }
println "Groovy".toUpperCase()
A programming language for grownups.
(with a silly name)
Monday, June 7, 2010

More Related Content

What's hot (19)

PPTX
Simple Jackson with DropWizard
Tatu Saloranta
 
PDF
Querydsl fin jug - june 2012
Timo Westkämper
 
PPTX
Js: master prototypes
Barak Drechsler
 
PPTX
Jackson beyond JSON: XML, CSV
Tatu Saloranta
 
PPT
Classes and Inheritance
emartinez.romero
 
PDF
Class notes(week 9) on multithreading
Kuntal Bhowmick
 
PDF
Objective-C Blocks and Grand Central Dispatch
Matteo Battaglio
 
PDF
[A 3]Javascript oop for xpages developers - public
Kazunori Tatsuki
 
PPT
Advanced Javascript
Adieu
 
PDF
Comparing JSON Libraries - July 19 2011
sullis
 
PDF
Excuse me, sir, do you have a moment to talk about tests in Kotlin
leonsabr
 
KEY
Xtext Eclipse Con
Sven Efftinge
 
PDF
Dependency Injection
ColdFusionConference
 
PDF
Patterns for JVM languages - Geecon 2014
Jaroslaw Palka
 
PDF
tutorial54
tutorialsruby
 
PDF
Concurrency on the JVM
Bernhard Huemer
 
PPT
Groovy Update - JavaPolis 2007
Guillaume Laforge
 
PPTX
Advanced JavaScript
Nascenia IT
 
Simple Jackson with DropWizard
Tatu Saloranta
 
Querydsl fin jug - june 2012
Timo Westkämper
 
Js: master prototypes
Barak Drechsler
 
Jackson beyond JSON: XML, CSV
Tatu Saloranta
 
Classes and Inheritance
emartinez.romero
 
Class notes(week 9) on multithreading
Kuntal Bhowmick
 
Objective-C Blocks and Grand Central Dispatch
Matteo Battaglio
 
[A 3]Javascript oop for xpages developers - public
Kazunori Tatsuki
 
Advanced Javascript
Adieu
 
Comparing JSON Libraries - July 19 2011
sullis
 
Excuse me, sir, do you have a moment to talk about tests in Kotlin
leonsabr
 
Xtext Eclipse Con
Sven Efftinge
 
Dependency Injection
ColdFusionConference
 
Patterns for JVM languages - Geecon 2014
Jaroslaw Palka
 
tutorial54
tutorialsruby
 
Concurrency on the JVM
Bernhard Huemer
 
Groovy Update - JavaPolis 2007
Guillaume Laforge
 
Advanced JavaScript
Nascenia IT
 

Similar to Groovy Metaprogramming for Dummies (20)

PPTX
Groovy And Grails Introduction
Eric Weimer
 
PDF
Greach 2014 - Metaprogramming with groovy
Iván López Martín
 
POT
intoduction to Grails Framework
Harshdeep Kaur
 
PDF
DSL's with Groovy
paulbowler
 
PDF
Practical Groovy DSL
Guillaume Laforge
 
PDF
GR8Conf 2009: Practical Groovy DSL by Guillaume Laforge
GR8Conf
 
PPT
Feelin' Groovy: An Afternoon of Reflexive Metaprogramming
Matt Stine
 
PDF
GR8Conf 2009: What's New in Groovy 1.6? by Guillaume Laforge
GR8Conf
 
PDF
Practical Domain-Specific Languages in Groovy
Guillaume Laforge
 
PPTX
getting-your-groovy-on
Christopher Johannsen
 
PDF
Groovy.pptx
Giancarlo Frison
 
KEY
Groovy & Grails
Marcel Overdijk
 
PDF
Groovy - Grails as a modern scripting language for Web applications
IndicThreads
 
PDF
Oscon Java Testing on the Fast Lane
Andres Almiray
 
PDF
Groovy On Trading Desk (2010)
Jonathan Felch
 
PDF
Groovy And Grails JUG Trento
John Leach
 
ODP
Groovy and Grails intro
Miguel Pastor
 
PPTX
Magic with groovy & grails
George Platon
 
PDF
Java Edge.2009.Grails.Web.Dev.Made.Easy
roialdaag
 
KEY
Polyglot Grails
Marcin Gryszko
 
Groovy And Grails Introduction
Eric Weimer
 
Greach 2014 - Metaprogramming with groovy
Iván López Martín
 
intoduction to Grails Framework
Harshdeep Kaur
 
DSL's with Groovy
paulbowler
 
Practical Groovy DSL
Guillaume Laforge
 
GR8Conf 2009: Practical Groovy DSL by Guillaume Laforge
GR8Conf
 
Feelin' Groovy: An Afternoon of Reflexive Metaprogramming
Matt Stine
 
GR8Conf 2009: What's New in Groovy 1.6? by Guillaume Laforge
GR8Conf
 
Practical Domain-Specific Languages in Groovy
Guillaume Laforge
 
getting-your-groovy-on
Christopher Johannsen
 
Groovy.pptx
Giancarlo Frison
 
Groovy & Grails
Marcel Overdijk
 
Groovy - Grails as a modern scripting language for Web applications
IndicThreads
 
Oscon Java Testing on the Fast Lane
Andres Almiray
 
Groovy On Trading Desk (2010)
Jonathan Felch
 
Groovy And Grails JUG Trento
John Leach
 
Groovy and Grails intro
Miguel Pastor
 
Magic with groovy & grails
George Platon
 
Java Edge.2009.Grails.Web.Dev.Made.Easy
roialdaag
 
Polyglot Grails
Marcin Gryszko
 
Ad

Recently uploaded (20)

PPTX
Heart Bleed Bug - A case study (Course: Cryptography and Network Security)
Adri Jovin
 
PPTX
Green Building & Energy Conservation ppt
Sagar Sarangi
 
PPTX
MobileComputingMANET2023 MobileComputingMANET2023.pptx
masterfake98765
 
PPTX
Presentation on Foundation Design for Civil Engineers.pptx
KamalKhan563106
 
PPTX
Innowell Capability B0425 - Commercial Buildings.pptx
regobertroza
 
PPTX
ISO/IEC JTC 1/WG 9 (MAR) Convenor Report
Kurata Takeshi
 
PDF
PORTFOLIO Golam Kibria Khan — architect with a passion for thoughtful design...
MasumKhan59
 
PDF
MOBILE AND WEB BASED REMOTE BUSINESS MONITORING SYSTEM
ijait
 
PDF
BioSensors glucose monitoring, cholestrol
nabeehasahar1
 
PPTX
MPMC_Module-2 xxxxxxxxxxxxxxxxxxxxx.pptx
ShivanshVaidya5
 
PPTX
原版一样(Acadia毕业证书)加拿大阿卡迪亚大学毕业证办理方法
Taqyea
 
PDF
Book.pdf01_Intro.ppt algorithm for preperation stu used
archu26
 
PPTX
Electron Beam Machining for Production Process
Rajshahi University of Engineering & Technology(RUET), Bangladesh
 
PDF
Unified_Cloud_Comm_Presentation anil singh ppt
anilsingh298751
 
PDF
Set Relation Function Practice session 24.05.2025.pdf
DrStephenStrange4
 
PPT
Oxygen Co2 Transport in the Lungs(Exchange og gases)
SUNDERLINSHIBUD
 
PPTX
site survey architecture student B.arch.
sri02032006
 
PDF
Introduction to Productivity and Quality
মোঃ ফুরকান উদ্দিন জুয়েল
 
PPTX
NEUROMOROPHIC nu iajwojeieheueueueu.pptx
knkoodalingam39
 
PPTX
Benefits_^0_Challigi😙🏡💐8fenges[1].pptx
akghostmaker
 
Heart Bleed Bug - A case study (Course: Cryptography and Network Security)
Adri Jovin
 
Green Building & Energy Conservation ppt
Sagar Sarangi
 
MobileComputingMANET2023 MobileComputingMANET2023.pptx
masterfake98765
 
Presentation on Foundation Design for Civil Engineers.pptx
KamalKhan563106
 
Innowell Capability B0425 - Commercial Buildings.pptx
regobertroza
 
ISO/IEC JTC 1/WG 9 (MAR) Convenor Report
Kurata Takeshi
 
PORTFOLIO Golam Kibria Khan — architect with a passion for thoughtful design...
MasumKhan59
 
MOBILE AND WEB BASED REMOTE BUSINESS MONITORING SYSTEM
ijait
 
BioSensors glucose monitoring, cholestrol
nabeehasahar1
 
MPMC_Module-2 xxxxxxxxxxxxxxxxxxxxx.pptx
ShivanshVaidya5
 
原版一样(Acadia毕业证书)加拿大阿卡迪亚大学毕业证办理方法
Taqyea
 
Book.pdf01_Intro.ppt algorithm for preperation stu used
archu26
 
Electron Beam Machining for Production Process
Rajshahi University of Engineering & Technology(RUET), Bangladesh
 
Unified_Cloud_Comm_Presentation anil singh ppt
anilsingh298751
 
Set Relation Function Practice session 24.05.2025.pdf
DrStephenStrange4
 
Oxygen Co2 Transport in the Lungs(Exchange og gases)
SUNDERLINSHIBUD
 
site survey architecture student B.arch.
sri02032006
 
Introduction to Productivity and Quality
মোঃ ফুরকান উদ্দিন জুয়েল
 
NEUROMOROPHIC nu iajwojeieheueueueu.pptx
knkoodalingam39
 
Benefits_^0_Challigi😙🏡💐8fenges[1].pptx
akghostmaker
 
Ad

Groovy Metaprogramming for Dummies

  • 1. Groovy Metaprogramming for Dummies Darren Cruse (not a professional speaker: please no heckling or throwing of food per Groovy User Group Regulation 103a subsection e) Monday, June 7, 2010
  • 2. Meta Stuff (about the meta talk) •Who am I? Once too good for “scripting” Former Perl Nut Recent Javascript Graduate Improving Groovy Skills Monday, June 7, 2010
  • 3. Meta Stuff (about the meta talk) •What’s this talk about? metaprogramming = “programming the program” metaprogramming = what makes groovy really groovy! Monday, June 7, 2010
  • 4. Meta Stuff (about the meta talk) • Who’s this talk for? Ideally: Someone who’s seen a bit of groovy and aspires to get to the next level Someone still unconvinced groovy’s power and productivity is sufficiently greater than java’s to merit learning a language with such a silly name. (and you advanced guys feel free to dive in and help me out!) Monday, June 7, 2010
  • 5. Builders = Metaprogramming Magic def builder = new StreamingMarkupBuilder() builder.encoding = 'UTF-8' def books = builder.bind { mkp.xmlDeclaration() namespaces << [meta:'http://meta/book/info'] books(count: 3) { book(id: 1) { title lang:'en', 'Groovy in Action' meta.isbn '1-932394-84-2' } book(id: 2) { title lang:'en', 'Groovy Programming' meta.isbn '0123725070' } book(id: 3) { title 'Groovy & Grails' comment << 'Not yet available.' } book(id: 4) { mkp.yieldUnescaped '<title>Griffon Guide</title>' } } } Monday, June 7, 2010
  • 6. Builders = Metaprogramming Magic <?xml version="1.0" encoding="UTF-8"?> <books xmlns:meta="http://meta/book/info" count="3"> <book id="1"> <title lang="en">Groovy in Action</title> <meta:isbn>1-932394-84-2</meta:isbn> </book> <book id="2"> <title lang="en">Groovy Programming</title> <meta:isbn>0123725070</meta:isbn> </book> <book id="3"> <title>Groovy &amp; Grails</title> <!--Not yet available.--> </book> <book id="4"> <title>Griffon Guide</title> </book> </books> Monday, June 7, 2010
  • 7. def builder = new StreamingMarkupBuilder() builder.encoding = 'UTF-8' def books = builder.bind { mkp.xmlDeclaration() namespaces << [meta:'http://meta/book/info'] books(count: 3) { book(id: 1) { title lang:'en', 'Groovy in Action' meta.isbn '1-932394-84-2' } book(id: 2) { title lang:'en', 'Groovy Programming' meta.isbn '0123725070' } book(id: 3) { title 'Groovy & Grails' comment << 'Not yet available.' } book(id: 4) { mkp.yieldUnescaped '<title>Griffon Guide</title>' } } } println XmlUtil.serialize(books) Builders = Metaprogramming Magic <?xml version="1.0" encoding="UTF-8"?> <books xmlns:meta="http://meta/book/info" count="3"> <book id="1"> <title lang="en">Groovy in Action</title> <meta:isbn>1-932394-84-2</meta:isbn> </book> <book id="2"> <title lang="en">Groovy Programming</title> <meta:isbn>0123725070</meta:isbn> </book> <book id="3"> <title>Groovy &amp; Grails</title> <!--Not yet available.--> </book> <book id="4"> <title>Griffon Guide</title> </book> </books> Monday, June 7, 2010
  • 8. book(id: 2) { title lang:'en', 'Groovy Programming' meta.isbn '0123725070' } XML Builders = An alternative Syntax for XML <book id="2"> <title lang="en">Groovy Programming</title> <meta:isbn>0123725070</meta:isbn> </book> Monday, June 7, 2010
  • 9. But How? (is it code or is it data?) Any sufficiently advanced technology is indistinguishable from magic. Arthur C. Clarke, English physicist & science fiction author (1917 - ) def builder = new StreamingMarkupBuilder() builder.encoding = 'UTF-8' def books = builder.bind { mkp.xmlDeclaration() namespaces << [meta:'http://meta/book/info'] books(count: 3) { book(id: 1) { title lang:'en', 'Groovy in Action' meta.isbn '1-932394-84-2' } book(id: 2) { title lang:'en', 'Groovy Programming' meta.isbn '0123725070' } book(id: 3) { title 'Groovy & Grails' // & is converted to &amp; comment << 'Not yet available.' } book(id: 4) { mkp.yieldUnescaped '<title>Griffon Guide</title>' } } } println XmlUtil.serialize(books) Monday, June 7, 2010
  • 10. The Answer Lies in Groovy’s Nature As a Dynamic Language (as distinguished from java) compile time Java run time compile time Groovy run time Monday, June 7, 2010
  • 13. The Program Generated... Evaluates Your Program At Runtime... ...it does so using a framework that is designed for you to plug into... When you do so you are “programming the program”... i.e. metaprogramming. Monday, June 7, 2010
  • 14. This framework is called the “Meta Object Protocol” (“protocol” in the sense of an “api”) MOPMonday, June 7, 2010
  • 15. If you’re familiar with a framework like Struts... This really isn’t that different: Instead of mapping url requests to the code that handles them, you’re mapping actual method calls and property accesses to the code that handles them! Instead of using struts-config.xml to do the mapping, you’re using actual code in the form of data structures called “meta classes” The simplest and coolest of these is called the ExpandoMetaClass! Monday, June 7, 2010
  • 16. All Groovy Objects Implement... public interface GroovyObject { Object invokeMethod(String name, Object args); Object getProperty(String propertyName); void setProperty(String propertyName, Object newValue); MetaClass getMetaClass(); void setMetaClass(MetaClass metaClass); } (This the heartbeat of the MOP) Monday, June 7, 2010
  • 17. MetaClasses Implement these methods for a class and thereby define the behavior of the class. Object invokeMethod(String name, Object args); Object getProperty(String propertyName); void setProperty(String propertyName, Object newValue); The beauty of ExpandoMetaClass is that you can add methods and properties to classes simply by assigning them - it expands indefinitely (like a Map). Monday, June 7, 2010
  • 18. So The Magic Is Revealed (dynamic dispatch and missing methods) <?xml version="1.0" encoding="UTF-8"?> <books xmlns:meta="http://meta/book/info" count="3"> <book id="1"> <title lang="en">Groovy in Action</title> <meta:isbn>1-932394-84-2</meta:isbn> </book> <book id="2"> <title lang="en">Groovy Programming</title> <meta:isbn>0123725070</meta:isbn> </book> <book id="3"> <title>Groovy &amp; Grails</title> <!--Not yet available.--> </book> <book id="4"> <title>Griffon Guide</title> </book> </books> def builder = new StreamingMarkupBuilder() builder.encoding = 'UTF-8' def books = builder.bind { mkp.xmlDeclaration() namespaces << [meta:'http://meta/book/info'] books(count: 3) { book(id: 1) { title lang:'en', 'Groovy in Action' meta.isbn '1-932394-84-2' } book(id: 2) { title lang:'en', 'Groovy Programming' meta.isbn '0123725070' } book(id: 3) { title 'Groovy & Grails' // & is converted to &amp; comment << 'Not yet available.' } book(id: 4) { mkp.yieldUnescaped '<title>Griffon Guide</title>' } } } println XmlUtil.serialize(books) Monday, June 7, 2010
  • 19. When it comes to Groovy’s syntax... What you can write is fixed by the parser (like most languages)... but there’s lots of optional stuff optional “()“, optional “;”, optional “[]” (sometimes)... so much optional it sounds nuts! but there’s a method to the madness. Monday, June 7, 2010
  • 20. Combining the MOP with Groovy’s loose syntax... You can highjack the meaning behind what the evaluator thinks are method or property calls but which supericially look more “declarative” than imperative more “what” than “how” the result can be shorter and clearer than java Monday, June 7, 2010
  • 21. Grails uses this stuff a lot... It has a lot of these “domain specific languages” or “DSL”s but this talk is about groovy it’s not about grails But grails is the best example of where these approaches are used all over the place to do amazing things with just a little code... so this talk is about grails DSL But it’s not it’s about how grails does things under the covers about how *groovy* does things under the covers so this is a meta talk about grails Exactly (exact-o-mundo) Monday, June 7, 2010
  • 22. And DSLs aren’t the only thing The combination of closures and metaclasses can allow much coolness including: AOP IOC Memoization RMI via REST (well, at least the factory pattern) (a fancy word for caching) (how many acronyms you gonna use?) (without the AOP) (coolness = productivity) Monday, June 7, 2010
  • 23. The preceding will be demonstrated with some delightful code examples. But first... Monday, June 7, 2010
  • 24. A Review of Closures for Newbies... A java assignment: int val = 3; A java function: public int func(int a, int b) { return a + b; } Or in Groovy: def val = 3 A groovy function: def func(a, b) { a + b } Monday, June 7, 2010
  • 25. A Review of Closures for Newbies... def func = (a, b) { a + b } Closures are anonymous functions that can be assigned as *values*... From the previously slide you can *almost* guess the syntax: Close! Above itʼs the variable that holds the name so itʼs on the left thatʼs correct. The wrong part is the parameters: def func = { a, b -> a + b } Groovyʼs syntax is nice because the “{“ and “}” clearly mark the “code block”. Monday, June 7, 2010
  • 26. A Review of Closures for Newbies... def class Counter { int count def increment = { count ++ } } One more thing about closures - regarding scoping... A closure defined in the lexical scope of other code can refer to itʼs variables. This surrounding code is the “owner”: But when closures are assigned to other objects, thereʼs more to life than just the surrounding code - esp. note the delegate: this: as in Java, this refers to the instance of the enclosing class where a Closure is defined owner : the enclosing object (this or a surrounding Closure) delegate : by default the same as owner, but changeable for example in a builder or ExpandoMetaClass Monday, June 7, 2010
  • 27. A Review of Closures for Newbies... def postiveOnly(Closure c) { list.each { val -> if(val > 0) c.call(val) } } Oh! And one more thing about closures... Groovy has syntactic sugar which allows a function taking a closure as itʼs final argument can be called with the closure passed after the functions closing paren: Can be called like so: postiveOnly { val -> println “$val is > 0” } And lastly: the default parameter if none is specified is simply “it”: postiveOnly { println “$it is > 0” } Monday, June 7, 2010
  • 28. Finally: some real metaprogramming... String.metaClass.shout = { delegate.toUpperCase(); } println "Groovy".shout() Add a method to a class: And yes, you could even: (but just because you can doesnʼt mean you will) This just shows what a flexible and powerful language groovy is. postiveOnly { println “$it is > 0” } String.metaClass.toUpperCase = { delegate.toLowerCase(); } println "Groovy".toUpperCase() A programming language for grownups. (with a silly name) Monday, June 7, 2010