groovy up your code

35
LOGICAL SOFTWARE Human Capital | Enterprise Java | Research Rua Gago Coutinho nº4 B 2675-509 Odivelas T +351 21 931 50 33 F +351 21 931 82 52 E [email protected] Web www.logical-software.com GROOVY UP YOUR CODE Paulo Traça CTO [email protected]

Upload: paulo-traca

Post on 09-May-2015

2.059 views

Category:

Technology


2 download

DESCRIPTION

Logical Software presentatio at Sapo CodeBits 2007

TRANSCRIPT

Page 1: Groovy Up Your Code

LOGICAL SOFTWAREHuman Capital | Enterprise Java | Research

Rua Gago Coutinho nº4 B2675-509 Odivelas

T +351 21 931 50 33F +351 21 931 82 52

E [email protected]

Web www.logical-software.com

GROOVY UP YOUR CODEPaulo TraçaCTO

[email protected]

Page 2: Groovy Up Your Code

Groovy Up Your Code

Objectivos da Sessão

● Conhecer as principais potencialidade dos Groovy ● Perceber em que o Groovy pode ser útil

● “Be more Groovy” :-)

Page 3: Groovy Up Your Code

Groovy Up Your Code

Agenda● O que é o Groovy ?

● Será que preciso de mais uma linguagem de scripting ?

● Características Básicas

● Características Avançadas

● The Goodies

● Demos

● Conclusão

● Referências

● Q & A

Page 4: Groovy Up Your Code

Groovy Up Your Code

Agenda● O que é o Groovy ?

● Será que preciso de mais uma linguagem de scripting ?

● Características Básicas

● Características Avançadas

● Demos

● The Goodies

● Conclusão

● Referências

● Q & A

Page 5: Groovy Up Your Code

Groovy Up Your Code

O que é o Groovy ?

“JAVA ON STEROIDS ...” e não é ilegal...

“ Groovy is like a super version of Java. It can leverage Java's enterprise capabilities but also has cool productivity features like closures, builders and dynamic typing. If you are a developer, tester or script guru, you have to love Groovy.”

Page 6: Groovy Up Your Code

Groovy Up Your Code

O que é Groovy● Linguagem ágil para JVM

● Sintaxe idêntica Java, curva da aprendizagem baixa para prog.

Java

● Linguagem dinâmica, Orientada a objectos

● Características da linguagem derivadas do Ruby, Python e

SmallTalk

● JCP 241

Page 7: Groovy Up Your Code

Groovy Up Your Code

O que é Groovy

● Suporte para DSL's (Domain Specific Languages)

● Suporte para Shell/ Builds scripts [cat | grep ... / Ant DSL]

● Unit Testing and Mock Object “out of the Box”

● Totalmente compatível com JAVA objects e bibliotecas

● Compila directamente para JVM bytecode

Page 8: Groovy Up Your Code

Groovy Up Your Code

Agenda● O que é o Groovy ?

● Será que preciso de mais uma linguagem de scripting ?

● Características Básicas

● Características Avançadas

● Demos

● The Goodies

● Conclusão

● Referências

● Q & A

Page 9: Groovy Up Your Code

Groovy Up Your Code

Porque investir no Groovy ?

● Proliferação de linguagens de scripting

● “The c00l new guy” - Ruby / RoR

● “The c00l new guy – Take 2” JRuby

● Python, Smalltalk ... { fill in with your favorite scripting language }

Page 10: Groovy Up Your Code

Groovy Up Your Code

O que torna o Groovy diferente ?

● JAVA / JVM compatível

● Se sabes JAVA, praticamente sabes Groovy

● Não obriga um novo investimento para aprender uma nova linguagem /

nova sintaxe

● Tira partido de toda infra-estrutura JEE, com +10 anos de maturidade

● Deploy directo para qualquer container JEE

● Reutiliza todos o investimento feito a aprender um conjunto de tools em

volta da plataforma JAVA [Sprint / Hibernate / Maven / Ant / JPA..]

● Permite “Mix and Match” entre código JAVA e código Groovy

Page 11: Groovy Up Your Code

Groovy Up Your Code

O que torna o Groovy diferente ?● All the JAVA Good Stuff

● Threading, Security, debugging

● Annotations (ver 1.1-betas/RC*)

● Tipos estáticos e tipos dinâmicos “Duck Typing”

Page 12: Groovy Up Your Code

Groovy Up Your Code

The Landscape of JVM Languages

Java Friendly

Feature rich

Dynamic feature callfor dynamic types

Optional types

other

other

other

otherGroovy

Java bytecode calls for static type

Page 13: Groovy Up Your Code

Groovy Up Your Code

public class Filter {

public static void main (String [] args) {

List list = new ArrayList();list.add(“Rod”);list.add(“Neta”);list.add(“Eric”);list.add(“Missy”);

Filter filter = newFilter();List shorts = filter.filterLongerThan(list, 4);System.out.println(shorts.size());

Iterator it = shorts.iterator();

while(it.hasNext()) {System.out.println(it.next());

}} //main

public List filterLonger(List list, int lenght) {List result = new ArrayList();Iterator it = list.iterator();while(it.hasNext()) {

String item = it.next();if (item.length() <= length) {result.add(item);}

}} //filterLonger

} //Filter

Sample Code Java

Page 14: Groovy Up Your Code

Groovy Up Your Code

Sample Code Groovy

def list = [“Neeta”, “Rod”, “Eric”, “Missy”]

def shorts = list.findAll { it.size () <= 4 }

println shorts.size()

shorts.each { println it }

Page 15: Groovy Up Your Code

Groovy Up Your Code

Agenda● O que é o Groovy ?

● Será que preciso de mais uma linguagem de scripting ?

● Características Básicas

● Características Avançadas

● Demos

● The Goodies

● Conclusão

● Referências

● Q & A

Page 16: Groovy Up Your Code

Groovy Up Your Code

Características Básicas

●Tipos dinâmicos e tipos estáticos (opcionais)

●Sintaxe nativa para listas e mapas

●Ranges

●Closures

●Overloading de operadores

●Suporte para expressões regulares na linguagem

●Groovy SDK

Page 17: Groovy Up Your Code

Groovy Up Your Code

Características Básicas Tipos dinâmicos e tipos estáticos (opcionais) int myVar = 3

def myVar = “Welcome to CodeBits”

Sintaxe nativa para listas e mapas

def myList = [“Code”, “Bits” , 2007 ]

printf myList[0] -- Code

def myMap = [“CodeBits2007”: 400, “CodeBits:2008”:1100, “CodeBits:2008”:2000]

printf myMap[“CodeBits2007”] ou println myMap.CodeBits2007-- 400

Page 18: Groovy Up Your Code

Groovy Up Your Code

Características Básicas(cont.)Ranges

def alphabet = 'a'..'z'

for (letter in alphabet) {print letter + ' '

} -- a b c d e f g h i j k l m n o p q r s t u v w x y z

-----------------------------------------------------

for (count in 1..10) {print count + ' '

}

Page 19: Groovy Up Your Code

Groovy Up Your Code

Características Básicas(cont.)Closures

def simponsMap = ["Homer":"donuts", "Marge":"Big Blue Hair", "Lisa":"the Sax"]

simponsMap.each { name, what -> printf "$name Simpon likes $what.\n"}

-- Homer Simpon likes donuts.

-- Marge Simpon likes Big Blue Hair.

-- Lisa Simpon likes The Sax.

Overloading de operadores

def list = [1,2,3,4,5,6] + [7,8,9,10]

list.each { print it }

-- 12345678910

Page 20: Groovy Up Your Code

Groovy Up Your Code

Características Básicas(cont.)

Suporte para expressões regulares na linguagem

if ( “name” ==~ “na.*”) { println “It a Match!”}

// ----------------------------------------------------------- def regexp = /Paulo.*/

def name1 = "PauloSilva"def name2 = "JoseSilva"

def isFirstNamePaulo(name, reg) { if (name ==~ reg) { println "match\n"}}isFirstNamePaulo(name1, regexp)isFirstNamePaulo(name2, regexp)

Page 21: Groovy Up Your Code

Groovy Up Your Code

Características Básicas(cont.)

Groovy SDK - métodos extras ao JDK

● Manipulação de string

● center(), contains(), count(), each(), padLeft(), padRight(), getAt(), etc

● Manipulação de colecções

● reverseEach(), count(), collect(), join(),sort(), max(), min(), toList(), etc

● File

● EachFile(), withPrintWriter(), write(), getText(), etc

Page 22: Groovy Up Your Code

Groovy Up Your Code

Agenda● O que é o Groovy ?

● Será que preciso de mais uma linguagem de scripting ?

● Características Básicas

● Características Avançadas

● Demos

● The Goodies

● Conclusão

● Referências

● Q & A

Page 23: Groovy Up Your Code

Groovy Up Your Code

Características Avançadas● Suporte nativo para estruturas hierárquicas

● XML

● HTML

● ANT

● SWING

● Navegação segura

● Parâmetros com valores default

● Currying

Page 24: Groovy Up Your Code

Groovy Up Your Code

Características Avançadas (Cont.)● Suporte para estruturas hierárquicas

● Builders

● NodeBuilder

● DomBuilder

● SwingBuilder

● AntBuilder

● ...

● Relativamente fácil acrescentar novos

Page 25: Groovy Up Your Code

Groovy Up Your Code

Características Avançadas (Cont.)

● Navegação segura, com o operador (?)

def simpson = ["Homer": ["donuts":20, "bear":50, "cakes":40]]

println simpson.Homer.bear

-- 50

println simpson.marge.bear

-- NullPointerException

println simpson?.marge?.bear

-- null

Page 26: Groovy Up Your Code

Groovy Up Your Code

● Parâmetros com valores default

def getFullName(firstName = "Jose", lastName= "Silva") { return firstName + " " + lastName }

getFullName()

-- Jose Silva

getFullName(1,2)

-- 1 2

def getFullName(String firstName = "Jose", String lastName= "Silva") { .. }

Características Avançadas (Cont.)

Page 27: Groovy Up Your Code

Groovy Up Your Code

● Currying

def c1 = {name, age, location -> println "Hi, I'm $name, i have $age and i'm from $location."}

.......

def c2 = c1.curry("Paulo")

.......

def c3 = c2.curry(25)

println c3("Portugal")

-- Hi, I'm Paulo, i have 25 and i'm from Portugal.

Características Avançadas (Cont.)

Page 28: Groovy Up Your Code

Groovy Up Your Code

DEMO

“Let's get groovy”

Page 29: Groovy Up Your Code

Groovy Up Your Code

Agenda● O que é o Groovy ?

● Será que preciso de mais uma linguagem de scripting ?

● Características Básicas

● Características Avançadas

● Demos

● The Goodies

● Conclusão

● Referências

● Q & A

Page 30: Groovy Up Your Code

Groovy Up Your Code

The Goodies● Grails –Web framework

● Integração com Web Service

● GroovySoap (ver 1.0 )

● GroovyWS (ver 1.1-RC*)

● XML / RPC

● Unit Testing Integrado

● GroovyTestCase, GroovyMock

● Shell scripting

● Existem api disponíveis para pipes | cat | grep ...

● Groosh module

Page 31: Groovy Up Your Code

Groovy Up Your Code

The Goodies● Groovy Jabber-RPC

● Windows Active X ou COM [Scriptom 2.0 Beta]

Programar e controlar excel / office ...

● Suporte para SQL com GSQL Module

● Muito mais ...

● Tooling

● Eclipse

● Intellij IDEA

Page 32: Groovy Up Your Code

Groovy Up Your Code

Agenda● O que é o Groovy ?

● Será que preciso de mais uma linguagem de scripting ?

● Características Básicas

● Características Avançadas

● Demos

● The Goodies

● Conclusão

● Referências

● Q & A

Page 33: Groovy Up Your Code

Groovy Up Your Code

Conclusões● Óptima tool para programadores Java

● Pronta para projectos não “mission critical”

● massa critica

● Opção ao Ruby / Jruby

● Algumas partes ainda estão em beta, e falta alguma documentação

● “Lots of Rope to Hang Yourself”

Page 34: Groovy Up Your Code

Groovy Up Your Code

Referências● Web

● http://groovy.codehaus.org

● http://grails.org

● Books

● Groovy in Action- Manning 2007

● Getting Started with Grial – InfoQ by Jason Rudolph

● Groovy Recipes – Pragmatic Bookshelf

Page 35: Groovy Up Your Code

Groovy Up Your Code

Q & A