groovy.pptx

43
It is Java as it should be. Easy and intuitive, it offers new features unknown to its parent yet, and come up with those benefits that form the basis of the DSLs Giancarlo Frison Groovy Overview

Upload: giancarlo-frison

Post on 10-May-2015

677 views

Category:

Documents


0 download

DESCRIPTION

Groovy speech I held last year for introducing a new JVM language as substitute of Java. Easy and intuitive, it offers new features unknow to its parent yet.

TRANSCRIPT

Page 1: Groovy.pptx

It is Java as it should be. Easy and intuitive, it offers new features unknown to its parent yet, and come up with those benefits that form the basis of the DSLs

Giancarlo Frison

Groovy Overview

Page 2: Groovy.pptx

Groovy is a super vision of Java. It can leverage Java’s enterprise capabilities but also has closures and dynamic typing, without all ceremonial syntax needed in Java

● Introduction● Data types ● Language features● Closures● Meta programming

Page 3: Groovy.pptx

What is Groovy?

Page 4: Groovy.pptx

Groovy = Java – boiler plate code+ mostly dynamic typing

+ closures+ domain specific languages

Introduction

Page 5: Groovy.pptx

● Fully Object oriented● Closures: reusable and

assignable piece of code● Groovy Beans● Collection Literals (lists,

maps, ranges, regular expressions)

● Meta programming (MOP, Expando, AST transformations, Mixins/Categories)

● Gpath expressions ● Grep and switch● Builders (XML, Json, Swing,

Ant, Tests)● Additional operators (? Null

safe)● Default and named

arguments● String enhances● Osgi

Groovy Overview

Page 6: Groovy.pptx

● Grails Web framework inspired by Ruby on Rails

● Gradle The next generation build system

● Griffon Desktop framework inspired by Grails

● Grape Add dependencies to your classpath

● Gorm Grails ORM persistance framework

● Gpars Concurrency/parallelism library

Frameworks

Page 7: Groovy.pptx

Less tedious syntax

Page 8: Groovy.pptx

A better Java…

Page 9: Groovy.pptx

…a better Java…

Page 10: Groovy.pptx

…a better Java…

Page 11: Groovy.pptx

…a better Java…

Page 12: Groovy.pptx

…a better Java…

Page 13: Groovy.pptx

…a better Java…

Page 14: Groovy.pptx

…a better Java…

Page 15: Groovy.pptx

…a better Java.

Page 16: Groovy.pptx

Better JavaBeans…

Page 17: Groovy.pptx

…a better JavaBeans…

Page 18: Groovy.pptx

…a better JavaBeans.

Page 19: Groovy.pptx

Data Types

Page 20: Groovy.pptx

● Multi-line stringsdef tt = '''

She sells, sea shellsBy the sea shore''‘

● String interpolationdef fullname = “$name $surname”

● Regexsassert'-36'==~ ‘/^[+-]?\d+$/’

GStrings● Rangesassert fullname[0..5] == name

● Comparison operatorsa==b a +-* ba<=>b a[]

● Groovy-gdkhttp://groovy.codehaus.org/groovy-jdk/java/lang/String.html

Page 21: Groovy.pptx

● Literal syntaxlist = [3,new Date(),’Jan']assert list + list == list * 2

● Mapsmap = [a:1,b:2]assert map['a']==1 && map.b ==2

● Rangesdef ls = ‘a'..'z‘,nums = 0..<10assert ls.size+nums.size == 36

Collections● Overloading operatorslist << new Date()

● Loop closuresmap.each{key, value ->

println “$key : $value”}

● …loop closureseach, every, collect, any, inject, find, findAll,upto, downto, times, grep, reverseEach, eachMatch, eachWithIndex, eachLine eachFile, eachFileMatch…

Page 22: Groovy.pptx

● No more :BigDecimal.divide(BigDecimal right, <scale>,

BigDecimal.ROUND_HALF_UP)

● Insteadassert 1/2 == new java.math.BigDecimal("0.5")

Math operations

Page 23: Groovy.pptx

use ( groovy.time.TimeCategory ) { println 1.minute.from.now println 10.hours.ago println new Date() - 3.months

def duration = date1 - date2 println "days: ${duration.days}, Hours: ${duration.hours}"}

Dates

Page 24: Groovy.pptx

Language Features

Page 25: Groovy.pptx

● It can handle any kind of valueswitch (x) { case 'James':

break case 18..65:

break case ~/Gw?+e/:

break case Date:

break case ['John', 'Ringo', 'Paul', 'George']:

break default:}

Improved Switch

Page 26: Groovy.pptx

● Any expression could be used and evaluated whereas Java requires a boolean.

● Number 0 return false● Empty string, lists, maps, matchers return false● Null objects return false● Of course… boolean false return false

Groovy Truth

Page 27: Groovy.pptx

● Null-safe version of Java's '.' operator

people << new Person(name:'Harry')

biggestSalary = people.collect{ p -> p.job?.salary }.max()

println biggestSalary

Null Object Pattern

Page 28: Groovy.pptx

send(String from, String to, String subject, String body) { println "sender ${from}" println "sender ${to}" println "sender ${subject}" println "sender ${body}"}

send from:"[email protected]", to:"[email protected]", subject:"greetings", body:"Hello Goodbye"

Named arguments

Page 29: Groovy.pptx

def (a, b, c) = [10, 20, 'foo']assert a == 10 && b == 20 && c == 'foo‘

def geocode(String location) { // implementation returns [48.824068, 2.531733]}def (lat, long) = geocode(“Bassano del Grappa, Italia")

Multiple assignments

Page 30: Groovy.pptx

● expression language integrated into Groovy which allows parts of nested structured data to be identified.

● a.b.c -> for XML, yields all the <c> elements inside <b> inside <a>

def feed = new XmlSlurper().parse('http://gfrison.com/rss')println feed.channel.item[0].title

● a.b.c -> all POJOs, yields the <c> properties for all the <b> properties of <a> (sort of like a.getB().getC() in JavaBeans)

GPath

Page 31: Groovy.pptx

Closures

Page 32: Groovy.pptx

● Treats data structures and operations as Objectsdef clos = { println "hello!" }clos()

● Closures as method argumentsdef houston = {doit ->

(10..1).each{ count->doit(count)

}} houston{ println it }

Closures

Page 33: Groovy.pptx

● Groovy has 3 variables inside each closure for defining different classes in his scope:

● this: As in Java it refers to the closure itself.● owner: Enclosing object of the closure.● delegate: The same of the owner, but it can be replaced

● When a closure encounters a method call that it cannot handle itself, it automatically relays the invocation to its owner object. If this fails, it relays the invocation to its delegate.

Closure delegate

Page 34: Groovy.pptx

Closures for better design…

Page 35: Groovy.pptx

…more better design.

Page 36: Groovy.pptx

Meta Object Programming

Page 37: Groovy.pptx

● Runtime● ExpandoMetaClass● Closures● Categories

● Compile-time● AST Transformations

Groovy MOP

Page 38: Groovy.pptx

● Allow to dynamically add methods, properties…

String.metaClass.swapCase = {-> def sb = new StringBuffer() delegate.each { sb << (Character.isUpperCase(it as char) ? Character.toLowerCase(it as char) : Character.toUpperCase(it as char)) } sb.toString()}

println "hELLO wORLD".swapCase()

ExpandoMetaClass

Page 39: Groovy.pptx

● It is a container for everything added by developer

def bean = new Expando( name:"James", location:"London", id:123 )assert "James" == bean.nameassert 123 == bean.id

Expando

Page 40: Groovy.pptx

● Add functionalities to classes to make them more usableclass StringCategory { static String lower(String string) { return string.toLowerCase() }} use (StringCategory) { assert "test" == "TeSt".lower()}

use (groovy.time.TimeCategory ) { println 1.minute.from.now println 10.hours.ago println new Date() - 3.months}

Categories

Page 41: Groovy.pptx

● Grape@Grab('org.mortbay.jetty:jetty-embedded:6.1.0')def server = new Server(8080)println "Starting Jetty, press Ctrl+C to stop."server.start()

● Slf4j@Slf4jclass HelloWorld { def logHello() { log.info 'Hello World' }}

AST Examples

Page 42: Groovy.pptx

● compile-time metaprogramming capabilities allowing powerful flexibility at the language level, without a runtime performance penalty.

● Global transformations adding a jar● Local transformations by annotating code elements:@Immutable @Delegate @Log @Field @PackageScope @AutoClone @AutoExternalizable @ThreadInterrupt @TimedInterrupt @ConditionalInterrupt @ToString @EqualsAndHashCode @TupleConstructor @Canonical @InheritConstructors @WithReadLock @WithWriteLock @ListenerList @Singleton @Lazy @Newify @Category@Mixin @PackageScope @Grab @Bindable @Vetoable

AST Transformations

Page 43: Groovy.pptx

Giancarlo Frison - gfrison.com

Questions?

…and Happy coding!