SlideShare a Scribd company logo
1 of 18
GROOVY
A better Java
would be
Groovy
!=
Java Replacement

Relies on Java

Is slower than Java

Great for Prototypes and Scripting

Strives as an Embedded Language

Ideal for Domain Specific Languages
What is Groovy?

builds upon the strengths of Java but has
additional power features inspired by languages
like Python, Ruby and Smalltalk

increases developer productivity by reducing
scaffolding code when developing web, GUI,
database or console applications

seamlessly integrates with all existing Java
classes and libraries

compiles straight to Java bytecode so you can
use it anywhere you can use Java
As described at http://groovy.codehaus.org/
Why all of this noise?
import java.io.*;
public class HelloWorld
{
public static void main(String[] args) throws Exception
{
String fileName = "/home/wes/test.txt";
BufferedReader br = new BufferedReader(new FileReader(fileName));
try
{
String line = null;
while((line=br.readLine()) != null)
{
System.out.println(line);
}
}
finally
{
br.close();
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Shouldn't it be Simpler?
new File('/home/wes/test.txt').eachLine { println it }1

Eliminates the boilerplate code associated with Java

Provides convenient shortcuts and expressive syntax

Leverages extensive collection of Java libraries

Closures provides elegant, reusable solutions
Groovy's Strengths are Simple but Powerful
Closures are
Anonymous Functions
// define a closure
def myCalc = { numForCalc1,numForCalc2 -> numForCalc1 * numForCalc2 }
// define a method with closure as parameter
def doMyCalc(num1, num2, calculateClosure)
{
calculateClosure(num1,num2)
}
// these are all the same
println myCalc(10,20)
println doMyCalc(10,20,myCalc)
println doMyCalc(10,20,{ a, b -> a * b })
println doMyCalc(10,20) { a, b -> a * b }
// or we could provide alternate implementation of the calculation
println doMyCalc(10,20) { a, b -> a - b }
println doMyCalc(10,20) { a, b -> a + b }
println doMyCalc(10,20) { a, b -> b - a }
println doMyCalc(10,20) { a, b -> a ^ b }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
What's Missing? Optional?

Return Statements

last value in a method is an implicit return value

Parameter and Return Types

duck typing is supported

types are checked/enforced when present

Classes

still available for organization purposes

not required as an entry point

Compilation

groovyc can be used to compile groovy to class files

groovy executable provides dynamic runtime
Java from Groovy
public class Contact
{
private String name, email, phone;
public String getName() { return name; }
public void setName(String name){ this.name = name; }
public String getEmail() { return email; }
public void setEmail(String email){ this.email = email; }
public String getPhone() { return phone; }
public void setPhone(String phone) { this.phone = phone; }
}
Contact contact = new Contact(name: 'Wes',
email: 'wes@mail.com',
Phone : '123-123-1234');
println "Contact ${contact.name} at ${contact.email} or ${contact.phone}"
1
2
3
4
5
Contact.java
useContact.groovy
Groovy from Java
import groovy.lang.*;
public class GroovyEmbedded
{
static String formatContact(Contact contact, String format)
{
Binding binding = new Binding();
binding.setVariable("c", contact);
GroovyShell shell = new GroovyShell(binding);
return shell.evaluate("c.identity { "" + format + "" }").toString();
}
public static void main(String[] args) throws Exception
{
Contact contact = new Contact();
contact.setName("Wes");
contact.setPhone("123-123-1234");
contact.setEmail("wes@mail.com");
String format1 = "Name: ${name}, Email: ${email}, Phone: ${phone}";
String format2 = "${name} - p: ${phone} e: ${email}";
System.out.println("Format #1: " + formatContact(contact,format1));
System.out.println("Format #2: " + formatContact(contact,format2));
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
Metaprogramming

Add behavior dynamically at runtime

Change existing behavior at runtime

Handle missing behavior gracefully

Invoke behavior dynamically
What if the rules only applied when we wanted?
MetaClass
def testString1 = "This is a test string."
def testString2 = "This is ALSO a TEST string."
println "Test #1a: ${testString1}" // This is a test string.
println "Test #2a: ${testString2}" // This is ALSO a TEST string.
try
{
testString1.doTestThing()
}
catch(Exception ex)
{
println "Error: ${ex.class.name}" // groovy.lang.MissingMethodException
}
println "Implement doTestThing at the class level"
String.metaClass.doTestThing = { delegate - " test" }
println "Test #1b: ${testString1.doTestThing()}" // This is a string.
println "Test #2b: ${testString2.doTestThing()}" // This is ALSO a TEST string.
println "Implement doTestThing at the instance level"
testString2.metaClass.doTestThing = { delegate - ~"(?i) test" }
println "Test #1c: ${testString1.doTestThing()}" // This is a string.
println "Test #2c: ${testString2.doTestThing()}" // This is ALSO a string.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
Intercepting Method Calls
void methodMissing(String methodName, args)

Allows implementation to be provided when method not present
Object getProperty(String propertyName)

Allows interception of get methods when Groovy's object.property syntax used
void setProperty(String propertyName, Object newValue)

Allows interception of set methods when Groovy's object.property syntax used
Object invokeMethod(String methodName, args)

Same as methodMissing when methodMissing not present

Allows interception of all methods when GroovyInterceptable is implemented
Method Missing
class LikesItAll
{
def likesSports() { println "I play and watch lots of sports!" }
def likesMovies() { println "I see movies all the time!" }
def everythingElse = { println "I really like ${it} too!" }
def methodMissing(String name, args)
{
if(name =~ /^likes/)
everythingElse(name-"likes")
else
println "What?"
}
}
LikesItAll dude = new LikesItAll()
dude.likesMovies()
dude.likesBooks()
dude.likesSports()
dude.dislikesSomething()
dude.likesCars()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Results:
I see movies all the time!
I really like Books too!
I play and watch lots of sports!
What?
I really like Cars too!
GroovyInterceptable
class Bank implements GroovyInterceptable
{
def balance=0
def deposit(amt) { balance += amt }
def withdraw(amt) { balance -= amt }
def invokeMethod(String name, args)
{
def metaMethod = metaClass.getMetaMethod(name, args)
if(metaMethod)
{
metaClass.print "Performing ${name} of $${args[0]}"
return metaMethod.invoke(this, args)
}
metaClass.println "This bank does not support ${name}ing"
}
}
Bank bank = new Bank()
bank.deposit 100
bank.withdraw 20
bank.borrow 30
println "Balance is: $${bank.balance}"
Results:
Performing deposit of $100
Performing withdraw of $20
This bank does not support borrowing
Balance is: $80
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
WITHWITH
GROOVY
POWERPOWER COMESCOMES
GROOVY
RESPONSIBILITYRESPONSIBILITY
Gotcha! Polymorphism Differences
public class Poly
{
void test() { System.out.println("No params"); }
void test(Object test) { System.out.println("Object1"); }
}
public class PolyExt extends Poly
{
void test(Object test) { System.out.println("Object2"); }
void test(String test) { System.out.println("String"); }
public static void main(String[] args)
{
String a = "test";
Object b = a;
Poly poly = new PolyExt();
poly.test();
poly.test(a);
((PolyExt)poly).test(a);
poly.test(b);
((PolyExt)poly).test(b);
}
}
GROOVY
No params
String
String
String
String
JAVA
No params
Object2
String
Object2
Object2
Gotcha! GString's Lazy Evaluation
name = 'Bob'
howToContact = new StringBuffer("1231231234")
contactInfo = "${-> new Date()} - ${-> name} at ${howToContact}n"
contactList = contactInfo
println contactList
Thread.sleep 30000 // 30 seconds
howToContact.append " & 2342342345"
println contactList
Thread.sleep 30000 // 30 seconds
name = "Sue"
howToContact = howToContact.reverse()
contactList += contactInfo
println contactList
Results:
Fri Nov 05 19:12:56 MDT 2010 - Bob at 1231231234
Fri Nov 05 19:13:26 MDT 2010 - Bob at 1231231234 & 2342342345
Fri Nov 05 19:13:56 MDT 2010 - Sue at 5432432432 & 4321321321
Fri Nov 05 19:13:56 MDT 2010 - Sue at 5432432432 & 4321321321
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Further
GROOVY
Reading
Language: http://groovy.codehaus.org/
Web Dev: http://www.grails.org/
Embeded: http://soapui.org/userguide/functional/groovystep.html
DSL: http://www.slideshare.net/glaforge/practical-groovy-dsl
wes-williams.blogspot.com

More Related Content

What's hot

Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)HamletDRC
 
Advanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesAdvanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesGanesh Samarthyam
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with GroovyArturo Herrero
 
AST Transformations
AST TransformationsAST Transformations
AST TransformationsHamletDRC
 
Ast transformations
Ast transformationsAst transformations
Ast transformationsHamletDRC
 
What did you miss in Java from 9-13?
What did you miss in Java from 9-13?What did you miss in Java from 9-13?
What did you miss in Java from 9-13?relix1988
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)Pavlo Baron
 
JEEConf 2017 - Having fun with Javassist
JEEConf 2017 - Having fun with JavassistJEEConf 2017 - Having fun with Javassist
JEEConf 2017 - Having fun with JavassistAnton Arhipov
 
Unit testing without Robolectric, Droidcon Berlin 2016
Unit testing without Robolectric, Droidcon Berlin 2016Unit testing without Robolectric, Droidcon Berlin 2016
Unit testing without Robolectric, Droidcon Berlin 2016Danny Preussler
 
Java Bytecode for Discriminating Developers - JavaZone 2011
Java Bytecode for Discriminating Developers - JavaZone 2011Java Bytecode for Discriminating Developers - JavaZone 2011
Java Bytecode for Discriminating Developers - JavaZone 2011Anton Arhipov
 
The Ring programming language version 1.10 book - Part 49 of 212
The Ring programming language version 1.10 book - Part 49 of 212The Ring programming language version 1.10 book - Part 49 of 212
The Ring programming language version 1.10 book - Part 49 of 212Mahmoud Samir Fayed
 
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
 
The Ring programming language version 1.5.3 book - Part 39 of 184
The Ring programming language version 1.5.3 book - Part 39 of 184The Ring programming language version 1.5.3 book - Part 39 of 184
The Ring programming language version 1.5.3 book - Part 39 of 184Mahmoud Samir Fayed
 
Groovy and Grails intro
Groovy and Grails introGroovy and Grails intro
Groovy and Grails introMiguel Pastor
 
Grooscript gr8conf
Grooscript gr8confGrooscript gr8conf
Grooscript gr8confGR8Conf
 
Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2José Paumard
 

What's hot (20)

Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)
 
Advanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesAdvanced Debugging Using Java Bytecodes
Advanced Debugging Using Java Bytecodes
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with Groovy
 
Groovy!
Groovy!Groovy!
Groovy!
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
AST Transformations
AST TransformationsAST Transformations
AST Transformations
 
Ast transformations
Ast transformationsAst transformations
Ast transformations
 
What did you miss in Java from 9-13?
What did you miss in Java from 9-13?What did you miss in Java from 9-13?
What did you miss in Java from 9-13?
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
 
JEEConf 2017 - Having fun with Javassist
JEEConf 2017 - Having fun with JavassistJEEConf 2017 - Having fun with Javassist
JEEConf 2017 - Having fun with Javassist
 
Unit testing without Robolectric, Droidcon Berlin 2016
Unit testing without Robolectric, Droidcon Berlin 2016Unit testing without Robolectric, Droidcon Berlin 2016
Unit testing without Robolectric, Droidcon Berlin 2016
 
Java 8
Java 8Java 8
Java 8
 
Java Bytecode for Discriminating Developers - JavaZone 2011
Java Bytecode for Discriminating Developers - JavaZone 2011Java Bytecode for Discriminating Developers - JavaZone 2011
Java Bytecode for Discriminating Developers - JavaZone 2011
 
Java Concurrency by Example
Java Concurrency by ExampleJava Concurrency by Example
Java Concurrency by Example
 
The Ring programming language version 1.10 book - Part 49 of 212
The Ring programming language version 1.10 book - Part 49 of 212The Ring programming language version 1.10 book - Part 49 of 212
The Ring programming language version 1.10 book - Part 49 of 212
 
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
 
The Ring programming language version 1.5.3 book - Part 39 of 184
The Ring programming language version 1.5.3 book - Part 39 of 184The Ring programming language version 1.5.3 book - Part 39 of 184
The Ring programming language version 1.5.3 book - Part 39 of 184
 
Groovy and Grails intro
Groovy and Grails introGroovy and Grails intro
Groovy and Grails intro
 
Grooscript gr8conf
Grooscript gr8confGrooscript gr8conf
Grooscript gr8conf
 
Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2
 

Viewers also liked

How is Social Media changing Tech?
How is Social Media changing Tech?How is Social Media changing Tech?
How is Social Media changing Tech?LouisPagan
 
ESCAPES magazine, issue #1, summer 2008
ESCAPES magazine, issue #1, summer 2008ESCAPES magazine, issue #1, summer 2008
ESCAPES magazine, issue #1, summer 2008Romana Lilic
 
Perekonnanimede käänamine surmakuulutustes
Perekonnanimede käänamine surmakuulutustesPerekonnanimede käänamine surmakuulutustes
Perekonnanimede käänamine surmakuulutustesKeelekorraldus
 
Nimede eestistamine 1920
Nimede eestistamine 1920Nimede eestistamine 1920
Nimede eestistamine 1920Keelekorraldus
 
CnAdventure China School Trip
CnAdventure China School TripCnAdventure China School Trip
CnAdventure China School TripCnAdventure
 
Kohanimeseadus ja selle kajastusi ajakirjanduses
Kohanimeseadus ja selle kajastusi ajakirjandusesKohanimeseadus ja selle kajastusi ajakirjanduses
Kohanimeseadus ja selle kajastusi ajakirjandusesKeelekorraldus
 
Science item collection
Science item collectionScience item collection
Science item collectionXiomara Jones
 
Johannes voldemar veski
Johannes voldemar veskiJohannes voldemar veski
Johannes voldemar veskiKeelekorraldus
 
Presentation on Windows 8 Application at IIT, University of Dhaka
Presentation on Windows 8 Application at IIT, University of DhakaPresentation on Windows 8 Application at IIT, University of Dhaka
Presentation on Windows 8 Application at IIT, University of DhakaAmit Seal Ami
 
Introduction to Groovy (Serbian Developer Conference 2013)
Introduction to Groovy (Serbian Developer Conference 2013)Introduction to Groovy (Serbian Developer Conference 2013)
Introduction to Groovy (Serbian Developer Conference 2013)Joachim Baumann
 
Introduction To Groovy
Introduction To GroovyIntroduction To Groovy
Introduction To Groovymanishkp84
 
Keynote Presentation Mobile App Lifecycle and Ecosystem
Keynote Presentation Mobile App Lifecycle and EcosystemKeynote Presentation Mobile App Lifecycle and Ecosystem
Keynote Presentation Mobile App Lifecycle and EcosystemAmit Seal Ami
 
Groovy Tutorial
Groovy TutorialGroovy Tutorial
Groovy TutorialPaul King
 
An Introduction to Groovy for Java Developers
An Introduction to Groovy for Java DevelopersAn Introduction to Groovy for Java Developers
An Introduction to Groovy for Java DevelopersKostas Saidis
 
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
 

Viewers also liked (19)

Groovy Intro
Groovy IntroGroovy Intro
Groovy Intro
 
How is Social Media changing Tech?
How is Social Media changing Tech?How is Social Media changing Tech?
How is Social Media changing Tech?
 
ESCAPES magazine, issue #1, summer 2008
ESCAPES magazine, issue #1, summer 2008ESCAPES magazine, issue #1, summer 2008
ESCAPES magazine, issue #1, summer 2008
 
Perekonnanimede käänamine surmakuulutustes
Perekonnanimede käänamine surmakuulutustesPerekonnanimede käänamine surmakuulutustes
Perekonnanimede käänamine surmakuulutustes
 
Test power point
Test power pointTest power point
Test power point
 
Nimede eestistamine 1920
Nimede eestistamine 1920Nimede eestistamine 1920
Nimede eestistamine 1920
 
CnAdventure China School Trip
CnAdventure China School TripCnAdventure China School Trip
CnAdventure China School Trip
 
Kohanimeseadus ja selle kajastusi ajakirjanduses
Kohanimeseadus ja selle kajastusi ajakirjandusesKohanimeseadus ja selle kajastusi ajakirjanduses
Kohanimeseadus ja selle kajastusi ajakirjanduses
 
Science item collection
Science item collectionScience item collection
Science item collection
 
Johannes voldemar veski
Johannes voldemar veskiJohannes voldemar veski
Johannes voldemar veski
 
Presentation on Windows 8 Application at IIT, University of Dhaka
Presentation on Windows 8 Application at IIT, University of DhakaPresentation on Windows 8 Application at IIT, University of Dhaka
Presentation on Windows 8 Application at IIT, University of Dhaka
 
Introduction to Groovy (Serbian Developer Conference 2013)
Introduction to Groovy (Serbian Developer Conference 2013)Introduction to Groovy (Serbian Developer Conference 2013)
Introduction to Groovy (Serbian Developer Conference 2013)
 
NTFS and Inode
NTFS and InodeNTFS and Inode
NTFS and Inode
 
JAX-WS Basics
JAX-WS BasicsJAX-WS Basics
JAX-WS Basics
 
Introduction To Groovy
Introduction To GroovyIntroduction To Groovy
Introduction To Groovy
 
Keynote Presentation Mobile App Lifecycle and Ecosystem
Keynote Presentation Mobile App Lifecycle and EcosystemKeynote Presentation Mobile App Lifecycle and Ecosystem
Keynote Presentation Mobile App Lifecycle and Ecosystem
 
Groovy Tutorial
Groovy TutorialGroovy Tutorial
Groovy Tutorial
 
An Introduction to Groovy for Java Developers
An Introduction to Groovy for Java DevelopersAn Introduction to Groovy for Java Developers
An Introduction to Groovy for Java Developers
 
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
 

Similar to Groovy Basics

Javaone2008 Bof 5101 Groovytesting
Javaone2008 Bof 5101 GroovytestingJavaone2008 Bof 5101 Groovytesting
Javaone2008 Bof 5101 GroovytestingAndres Almiray
 
Boosting Your Testing Productivity with Groovy
Boosting Your Testing Productivity with GroovyBoosting Your Testing Productivity with Groovy
Boosting Your Testing Productivity with GroovyJames Williams
 
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
 
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
 
Introduction to Oracle Groovy
Introduction to Oracle GroovyIntroduction to Oracle Groovy
Introduction to Oracle GroovyDeepak Bhagat
 
Oscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast LaneOscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast LaneAndres Almiray
 
Polyglot Programming in the JVM
Polyglot Programming in the JVMPolyglot Programming in the JVM
Polyglot Programming in the JVMAndres Almiray
 
Real life-coffeescript
Real life-coffeescriptReal life-coffeescript
Real life-coffeescriptDavid Furber
 
Polyglot Programming @ Jax.de 2010
Polyglot Programming @ Jax.de 2010Polyglot Programming @ Jax.de 2010
Polyglot Programming @ Jax.de 2010Andres Almiray
 
Eclipsecon08 Introduction To Groovy
Eclipsecon08 Introduction To GroovyEclipsecon08 Introduction To Groovy
Eclipsecon08 Introduction To GroovyAndres Almiray
 
The Future of JVM Languages
The Future of JVM Languages The Future of JVM Languages
The Future of JVM Languages VictorSzoltysek
 
Groovy and Grails talk
Groovy and Grails talkGroovy and Grails talk
Groovy and Grails talkdesistartups
 
Not your father's tests
Not your father's testsNot your father's tests
Not your father's testsSean P. Floyd
 
Pick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruitPick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruitVaclav Pech
 
Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)Jonathan Felch
 
Groovy & Grails: Scripting for Modern Web Applications
Groovy & Grails: Scripting for Modern Web ApplicationsGroovy & Grails: Scripting for Modern Web Applications
Groovy & Grails: Scripting for Modern Web Applicationsrohitnayak
 

Similar to Groovy Basics (20)

Javaone2008 Bof 5101 Groovytesting
Javaone2008 Bof 5101 GroovytestingJavaone2008 Bof 5101 Groovytesting
Javaone2008 Bof 5101 Groovytesting
 
Boosting Your Testing Productivity with Groovy
Boosting Your Testing Productivity with GroovyBoosting Your Testing Productivity with Groovy
Boosting Your Testing Productivity with Groovy
 
Os Secoske
Os SecoskeOs Secoske
Os Secoske
 
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
 
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
 
Introduction to Oracle Groovy
Introduction to Oracle GroovyIntroduction to Oracle Groovy
Introduction to Oracle Groovy
 
Svcc Groovy Testing
Svcc Groovy TestingSvcc Groovy Testing
Svcc Groovy Testing
 
Oscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast LaneOscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast Lane
 
Polyglot Programming in the JVM
Polyglot Programming in the JVMPolyglot Programming in the JVM
Polyglot Programming in the JVM
 
Real life-coffeescript
Real life-coffeescriptReal life-coffeescript
Real life-coffeescript
 
Griffon @ Svwjug
Griffon @ SvwjugGriffon @ Svwjug
Griffon @ Svwjug
 
Polyglot Programming @ Jax.de 2010
Polyglot Programming @ Jax.de 2010Polyglot Programming @ Jax.de 2010
Polyglot Programming @ Jax.de 2010
 
Eclipsecon08 Introduction To Groovy
Eclipsecon08 Introduction To GroovyEclipsecon08 Introduction To Groovy
Eclipsecon08 Introduction To Groovy
 
The Future of JVM Languages
The Future of JVM Languages The Future of JVM Languages
The Future of JVM Languages
 
Groovy and Grails talk
Groovy and Grails talkGroovy and Grails talk
Groovy and Grails talk
 
Not your father's tests
Not your father's testsNot your father's tests
Not your father's tests
 
Pick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruitPick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruit
 
Groovy
GroovyGroovy
Groovy
 
Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)
 
Groovy & Grails: Scripting for Modern Web Applications
Groovy & Grails: Scripting for Modern Web ApplicationsGroovy & Grails: Scripting for Modern Web Applications
Groovy & Grails: Scripting for Modern Web Applications
 

Recently uploaded

Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 

Recently uploaded (20)

Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 

Groovy Basics

  • 2. Groovy != Java Replacement  Relies on Java  Is slower than Java  Great for Prototypes and Scripting  Strives as an Embedded Language  Ideal for Domain Specific Languages
  • 3. What is Groovy?  builds upon the strengths of Java but has additional power features inspired by languages like Python, Ruby and Smalltalk  increases developer productivity by reducing scaffolding code when developing web, GUI, database or console applications  seamlessly integrates with all existing Java classes and libraries  compiles straight to Java bytecode so you can use it anywhere you can use Java As described at http://groovy.codehaus.org/
  • 4. Why all of this noise? import java.io.*; public class HelloWorld { public static void main(String[] args) throws Exception { String fileName = "/home/wes/test.txt"; BufferedReader br = new BufferedReader(new FileReader(fileName)); try { String line = null; while((line=br.readLine()) != null) { System.out.println(line); } } finally { br.close(); } } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
  • 5. Shouldn't it be Simpler? new File('/home/wes/test.txt').eachLine { println it }1  Eliminates the boilerplate code associated with Java  Provides convenient shortcuts and expressive syntax  Leverages extensive collection of Java libraries  Closures provides elegant, reusable solutions Groovy's Strengths are Simple but Powerful
  • 6. Closures are Anonymous Functions // define a closure def myCalc = { numForCalc1,numForCalc2 -> numForCalc1 * numForCalc2 } // define a method with closure as parameter def doMyCalc(num1, num2, calculateClosure) { calculateClosure(num1,num2) } // these are all the same println myCalc(10,20) println doMyCalc(10,20,myCalc) println doMyCalc(10,20,{ a, b -> a * b }) println doMyCalc(10,20) { a, b -> a * b } // or we could provide alternate implementation of the calculation println doMyCalc(10,20) { a, b -> a - b } println doMyCalc(10,20) { a, b -> a + b } println doMyCalc(10,20) { a, b -> b - a } println doMyCalc(10,20) { a, b -> a ^ b } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
  • 7. What's Missing? Optional?  Return Statements  last value in a method is an implicit return value  Parameter and Return Types  duck typing is supported  types are checked/enforced when present  Classes  still available for organization purposes  not required as an entry point  Compilation  groovyc can be used to compile groovy to class files  groovy executable provides dynamic runtime
  • 8. Java from Groovy public class Contact { private String name, email, phone; public String getName() { return name; } public void setName(String name){ this.name = name; } public String getEmail() { return email; } public void setEmail(String email){ this.email = email; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } } Contact contact = new Contact(name: 'Wes', email: 'wes@mail.com', Phone : '123-123-1234'); println "Contact ${contact.name} at ${contact.email} or ${contact.phone}" 1 2 3 4 5 Contact.java useContact.groovy
  • 9. Groovy from Java import groovy.lang.*; public class GroovyEmbedded { static String formatContact(Contact contact, String format) { Binding binding = new Binding(); binding.setVariable("c", contact); GroovyShell shell = new GroovyShell(binding); return shell.evaluate("c.identity { "" + format + "" }").toString(); } public static void main(String[] args) throws Exception { Contact contact = new Contact(); contact.setName("Wes"); contact.setPhone("123-123-1234"); contact.setEmail("wes@mail.com"); String format1 = "Name: ${name}, Email: ${email}, Phone: ${phone}"; String format2 = "${name} - p: ${phone} e: ${email}"; System.out.println("Format #1: " + formatContact(contact,format1)); System.out.println("Format #2: " + formatContact(contact,format2)); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
  • 10. Metaprogramming  Add behavior dynamically at runtime  Change existing behavior at runtime  Handle missing behavior gracefully  Invoke behavior dynamically What if the rules only applied when we wanted?
  • 11. MetaClass def testString1 = "This is a test string." def testString2 = "This is ALSO a TEST string." println "Test #1a: ${testString1}" // This is a test string. println "Test #2a: ${testString2}" // This is ALSO a TEST string. try { testString1.doTestThing() } catch(Exception ex) { println "Error: ${ex.class.name}" // groovy.lang.MissingMethodException } println "Implement doTestThing at the class level" String.metaClass.doTestThing = { delegate - " test" } println "Test #1b: ${testString1.doTestThing()}" // This is a string. println "Test #2b: ${testString2.doTestThing()}" // This is ALSO a TEST string. println "Implement doTestThing at the instance level" testString2.metaClass.doTestThing = { delegate - ~"(?i) test" } println "Test #1c: ${testString1.doTestThing()}" // This is a string. println "Test #2c: ${testString2.doTestThing()}" // This is ALSO a string. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
  • 12. Intercepting Method Calls void methodMissing(String methodName, args)  Allows implementation to be provided when method not present Object getProperty(String propertyName)  Allows interception of get methods when Groovy's object.property syntax used void setProperty(String propertyName, Object newValue)  Allows interception of set methods when Groovy's object.property syntax used Object invokeMethod(String methodName, args)  Same as methodMissing when methodMissing not present  Allows interception of all methods when GroovyInterceptable is implemented
  • 13. Method Missing class LikesItAll { def likesSports() { println "I play and watch lots of sports!" } def likesMovies() { println "I see movies all the time!" } def everythingElse = { println "I really like ${it} too!" } def methodMissing(String name, args) { if(name =~ /^likes/) everythingElse(name-"likes") else println "What?" } } LikesItAll dude = new LikesItAll() dude.likesMovies() dude.likesBooks() dude.likesSports() dude.dislikesSomething() dude.likesCars() 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 Results: I see movies all the time! I really like Books too! I play and watch lots of sports! What? I really like Cars too!
  • 14. GroovyInterceptable class Bank implements GroovyInterceptable { def balance=0 def deposit(amt) { balance += amt } def withdraw(amt) { balance -= amt } def invokeMethod(String name, args) { def metaMethod = metaClass.getMetaMethod(name, args) if(metaMethod) { metaClass.print "Performing ${name} of $${args[0]}" return metaMethod.invoke(this, args) } metaClass.println "This bank does not support ${name}ing" } } Bank bank = new Bank() bank.deposit 100 bank.withdraw 20 bank.borrow 30 println "Balance is: $${bank.balance}" Results: Performing deposit of $100 Performing withdraw of $20 This bank does not support borrowing Balance is: $80 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
  • 16. Gotcha! Polymorphism Differences public class Poly { void test() { System.out.println("No params"); } void test(Object test) { System.out.println("Object1"); } } public class PolyExt extends Poly { void test(Object test) { System.out.println("Object2"); } void test(String test) { System.out.println("String"); } public static void main(String[] args) { String a = "test"; Object b = a; Poly poly = new PolyExt(); poly.test(); poly.test(a); ((PolyExt)poly).test(a); poly.test(b); ((PolyExt)poly).test(b); } } GROOVY No params String String String String JAVA No params Object2 String Object2 Object2
  • 17. Gotcha! GString's Lazy Evaluation name = 'Bob' howToContact = new StringBuffer("1231231234") contactInfo = "${-> new Date()} - ${-> name} at ${howToContact}n" contactList = contactInfo println contactList Thread.sleep 30000 // 30 seconds howToContact.append " & 2342342345" println contactList Thread.sleep 30000 // 30 seconds name = "Sue" howToContact = howToContact.reverse() contactList += contactInfo println contactList Results: Fri Nov 05 19:12:56 MDT 2010 - Bob at 1231231234 Fri Nov 05 19:13:26 MDT 2010 - Bob at 1231231234 & 2342342345 Fri Nov 05 19:13:56 MDT 2010 - Sue at 5432432432 & 4321321321 Fri Nov 05 19:13:56 MDT 2010 - Sue at 5432432432 & 4321321321 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
  • 18. Further GROOVY Reading Language: http://groovy.codehaus.org/ Web Dev: http://www.grails.org/ Embeded: http://soapui.org/userguide/functional/groovystep.html DSL: http://www.slideshare.net/glaforge/practical-groovy-dsl wes-williams.blogspot.com