introduccion a groovy- daniel ortega

51
GROOVY INTRODUCTION WAY MORE THAN JAVA WITHOUT SEMICOLONS

Upload: oracle-espana

Post on 14-Apr-2017

538 views

Category:

Technology


5 download

TRANSCRIPT

Page 1: Introduccion a Groovy- Daniel Ortega

GROOVY INTRODUCTIONWAY MORE THAN JAVA WITHOUT

SEMICOLONS

Page 2: Introduccion a Groovy- Daniel Ortega

ABOUT MEFullStack developer w/ +10 years of experienceOfficial Sun Microsystems InstructorGroovy Taliban since 2009Angular JS lover since 2013Meat Lover

enthusiastWerken voor

#FreeBaconGuitar

KLM

SOCIAL@olmaygtiLinkedIn ProfileGitHub ProfileBitbucket Profile

Page 3: Introduccion a Groovy- Daniel Ortega

EAT MEAT

Page 4: Introduccion a Groovy- Daniel Ortega

ABOUT THISPRESENTATION

FrontEnd Backend

Slideshow Powered

Source code available at Live at (at leasttoday)

SPAAngularJSGrailsReveal.jsGroovy

GitHubhttp://oracle-olmaygti.rhcloud.com/

Page 5: Introduccion a Groovy- Daniel Ortega

WHAT IS GROOVY?

Page 6: Introduccion a Groovy- Daniel Ortega

WHAT IS GROOVY?Groovy is what Java would look like if it had been invented in

the 21st century"

Scott Davis

Page 7: Introduccion a Groovy- Daniel Ortega

WHAT IS GROOVY?Groovy is a for the Java Platformdynamic language

Page 8: Introduccion a Groovy- Daniel Ortega

WHAT IS GROOVY?Groovy is a for the Java Platform:dynamic language

Duck TypingDynamic Method Invokation Resolution ( )ClosuresPowerful scripting capabilitiesEnhanced JDK ( )DSL friendlyIntrospection and metaprogramming made easy!

MOP

GDK

Page 9: Introduccion a Groovy- Daniel Ortega

WHAT IS GROOVY?Groovy Syntax is a super set of Java Syntax

We all are Groovy devs!

Page 10: Introduccion a Groovy- Daniel Ortega

WHAT IS GROOVY?Groovy Syntax is a super set of Java Syntax

We all are Groovy devs!Optional

SemicolonsParenthesesreturn keywordpublic keyword (default for classes and methods)private keyword (default for class attributes)

Page 11: Introduccion a Groovy- Daniel Ortega

WHAT IS GROOVY?Groovy Syntax is a super set of Java Syntax

We all are Groovy devs!Optional

SemicolonsParenthesesreturn keywordpublic keyword (default for classes and methods)private keyword (default for class attributes)

Getters and Setters generationDot operator (.)

If parentheses uses will try to invoke the given methodIf not, will invoke the getter

Page 12: Introduccion a Groovy- Daniel Ortega

JAVA TO GROOVYTHE JAVA WAY

public class GroovyExample private String variable;

public String getVariable() return variable;

public void setVariable(String variable) this.variable = variable;

public String myMethod() return this.variable != null ? this.variable : "Not initialised";

GroovyExample ref = new GroovyExample();System.out.println(ref.getVariable());System.out.println(ref.myMethod());

Page 13: Introduccion a Groovy- Daniel Ortega

JAVA TO GROOVYNO SEMICOLONS!

public class GroovyExample private String variable

public String getVariable() return variable

public void setVariable(String variable) this.variable = variable

public String myMethod() return this.variable != null ? this.variable : "Not initialised"

GroovyExample ref = new GroovyExample()System.out.println(ref.getVariable())System.out.println(ref.myMethod())

Page 14: Introduccion a Groovy- Daniel Ortega

JAVA TO GROOVYDEFAULT PUBLIC ACCESSORS

class GroovyExample private String variable

String getVariable() return variable

void setVariable(String variable) this.variable = variable

String myMethod() return this.variable != null ? this.variable : "Not initialised"

GroovyExample ref = new GroovyExample()System.out.println(ref.getVariable())System.out.println(ref.myMethod())

Page 15: Introduccion a Groovy- Daniel Ortega

JAVA TO GROOVYGETTERS&SETTERS OUT!

class GroovyExample String variable

String myMethod() return this.variable != null ? this.variable : "Not initialised"

GroovyExample ref = new GroovyExample()System.out.println(ref.getVariable())System.out.println(ref.myMethod())

Page 16: Introduccion a Groovy- Daniel Ortega

JAVA TO GROOVYPARENTHESES OPTIONALS

class GroovyExample String variable

String myMethod() return this.variable != null ? this.variable : "Not initialised"

GroovyExample ref = new GroovyExample()println ref.getVariable()println ref.myMethod()

Page 17: Introduccion a Groovy- Daniel Ortega

JAVA TO GROOVYTHE GROOVY WAY!

class GroovyExample String variable

String myMethod() this.variable ?: "Not initialised"

def ref = new GroovyExample()println ref.variableprintln ref.myMethod()

Page 18: Introduccion a Groovy- Daniel Ortega

JAVA TO GROOVYTHE JAVA WAY

public class GroovyExample private String variable;

public String getVariable() return variable;

public void setVariable(String variable) this.variable = variable;

public String myMethod() return this.variable != null ? this.variable : "Not initialised";

GroovyExample ref = new GroovyExample();System.out.println(ref.getVariable());System.out.println(ref.myMethod());

Page 19: Introduccion a Groovy- Daniel Ortega
Page 20: Introduccion a Groovy- Daniel Ortega

CLOSURESA closure is just a piece of code that can be referencedJava 8 Lambdas are nice, but they came too lateEssential part of the language, they are used every whereJust syntactic sugar for inline Anonymous Inner ClassesTake a look at the API

Page 21: Introduccion a Groovy- Daniel Ortega

TEST IT OUT!def myCollection = [1,2,3,4];myCollection.each println it;def square = it**2 ;myCollection.collect(square)

Execute

Page 22: Introduccion a Groovy- Daniel Ortega

HOW DOES THIS WORK?public interface Collection ... public void each(Closure closure) for (Object obj: this.collection) closure.call(obj); myCollection.each(new Closure() public void call(Object obj) System.out.println(obj); );

Page 23: Introduccion a Groovy- Daniel Ortega

GROOVY TYPES AND LITERALSThere are not primitive types in Groovy

Everything is an objectNumbers fall under the best fitter (Integer, Double,BigDecimal...)boolean literals are instance of the Boolean classSpecial inline syntax for collections

[] for ArrayList[:] for HashMap

Strings are special ...

Page 24: Introduccion a Groovy- Daniel Ortega

GROOVY STRINGS LITERALSThere are multiple ways to declare a String literal in Groovy

Single quoted: 'this is a String'Double quoted: "this is a String, but not always"Slashy Strings: /This is really handy for regexps!/Dollar-Slashy Strings: $/Really?/$You can declare multiline Strings with triple single/doublequotes

Page 25: Introduccion a Groovy- Daniel Ortega

TEST IT OUT!def myVar = 'Oracle';[5.class, 5l.class, 'h'.class, true.class, 'Hello world!', '''multilinestring'''.class, "This is not a String $myVar".class,[].class, [:].class]

Execute

Page 26: Introduccion a Groovy- Daniel Ortega

THE GROOVY TRUTHIn Groovy everything can be evaluated in a boolean context

References are false if pointing to null, true otherwhiseCollections are also false if emptyAnd so are stringsNon zero values are also true when working with numbersMatchers are true if they have at least one match

Page 27: Introduccion a Groovy- Daniel Ortega

GROOVY OPERATORSGroovy supports all Java regular operators

ArithmeticUnaryRelationalLogicalBitwiseTernary Operator

Important to notice that the == will always delegate on the equals() method

Page 28: Introduccion a Groovy- Daniel Ortega

GROOVY SPECIAL OPERATORSELVIS OPERATOR ?:

The elvis operator is a shortcut for the ternary operator,taking advtange of the groovy truth

if (reference != null) return reference; else return 'defaultValue'; // Java Ternary return reference != null ? reference : 'defaultValue'; // Groovy ternary with groovy truth return reference ? reference : 'defaultValue' // Groovy Elvis Operator reference ?: 'defaultValue'

Page 29: Introduccion a Groovy- Daniel Ortega

GROOVY SPECIAL OPERATORSSAFE NAVIGATION OPERATOR ?.

Comes handy to avoid lots of if (variable != null)

// Java way if (reference != null && reference.getAttribute1() != null) return reference.getAttribute1().getAttribute2(); // Groovy way reference?.attribute1?.attribute2

Page 30: Introduccion a Groovy- Daniel Ortega

GROOVY SPECIAL OPERATORSSPACESHIFT OPERATOR <=>

Shortcut for compareTo() calls

assert (1 <=> 1) == 0assert (1 <=> 2) == ­1assert (2 <=> 1) == 1assert ('a' <=> 'z') == ­1

Page 31: Introduccion a Groovy- Daniel Ortega

GROOVY SPECIAL OPERATORSREGULAR EXPRESSIONS OPERATORS =~ AND ==~

The first one will return an instance of Matcher whilst the second onereturns boolean value

assert "abcd" ==~ /a.*$/

def matcher = "abcd" =~ /(a).*$/ assert matcher[0][1] == 'a'

Page 32: Introduccion a Groovy- Daniel Ortega

GROOVY SPECIAL OPERATORSSPREAD OPERATOR .*

Invokes an action on all elements off a collection

class Car String make String modeldef cars = [ new Car(make: 'Peugeot', model: '508'), new Car(make: 'Renault', model: 'Clio')] assert cars*.getMake() == ['Peugeot', 'Renault']assert cars.model == ['508', 'Clio']

Page 33: Introduccion a Groovy- Daniel Ortega

GROOVY SPECIAL OPERATORSDIRECT FIELD ACCCESS OPERATOR .@

Dot operator will always delegate on the proper setter when used.

Use this operator if you want to directly access the attribute value.

Take into consideration that visibility modifiers apply the same way as inJava

class Test public String attribute

def getAttribute() "$this.attribute ­ $this.attribute" def test = new Test()// Implicit setter calltest.attribute = 'testString'// Implicit getter callassert test.attribute == 'testString ­ testString'// Direct field accessassert test.@attribute = 'testString'

Page 34: Introduccion a Groovy- Daniel Ortega

GROOVY SPECIAL OPERATORSMETHOD OPERATOR .&

Stores a reference to a class methoddef powerList = [2, 3];powerList.collect(java.lang.Math.&pow.curry(2))

Page 35: Introduccion a Groovy- Daniel Ortega

GROOVY SPECIAL OPERATORSThese are just a subset of all the operators GroovyintroducesGroovy supports operator overloading!

Just implement the method add() in your classes!Take a look at the documentation

Page 36: Introduccion a Groovy- Daniel Ortega

MULTIMETHODSBecause of the dynamic nature of Groovy, the execution of this code will

delegate on the proper method at runtime, whereas Java would take thatdecision at compile time

int method(String arg) return 1;int method(Object arg) return 2;Object o = "Object";int result = method(o);

Page 37: Introduccion a Groovy- Daniel Ortega

GDK ENHANCEMENTSThe Groovy Development Kit exposes many enhancementsover the JDK APICheck the Or the

Collections APIFile API

Page 38: Introduccion a Groovy- Daniel Ortega

GDK ENHANCEMENTSCOLLECTIONS API

def users = [ new User(name: 'Bill', city: 'Washintong', age: 50), new User(name: 'Barack', city: 'Chicago', age: 43), new User(name: 'Ronald', city: 'New York', age: 99), new User(name: 'George', city: 'oLs Angeles', age: 80), new User(name: 'GeorgeJr', city: 'Los Angeles', age: 60),]// Simple order by ageusers.sort a, b ­> a.age <=> b.age// All different citiesusers.city.unique()// People from LAusers.findAll it.city == 'Los Angeles'// Population ages by cityusers.groupBy it."city".collect key, value ­> [key: value.age]

Page 39: Introduccion a Groovy- Daniel Ortega

GDK ENHANCEMENTSFILE API

// Reading contents of a given File line by linenew File('routeToFile').eachLine println it // Impossible to be this easy!def contents new File('routeToFile').text// And write those contents to another file ...new File('thisDoesntExist') << contents// Recursively list all files inside a foldernew File('routeToFile').eachFileRecursive println it

Page 40: Introduccion a Groovy- Daniel Ortega

WHERE ARE THE BUFFERED READERS AND THETRY/CATCH STATEMENTS?

NEITHER CHECKED NOR UNCHECKED EXCEPTIONS NEED TO BECAUGHT

Page 41: Introduccion a Groovy- Daniel Ortega

METAPROGRAMMINGGroovy easily allows the developer to

manipulate/introspect loaded classes at runtime

The metaClass is the entry point of this obscure worldUses the under the hoodReflections API

Page 42: Introduccion a Groovy- Daniel Ortega

TEST IT OUT!java.lang.Object.metaClass.methods

Execute

Page 43: Introduccion a Groovy- Daniel Ortega

THIS IS JUST THE BEGINNING OF THE JOURNEY MY FRIEND ...

Page 44: Introduccion a Groovy- Daniel Ortega

METAPROGRAMMINGINTRODUCING MOP

The specifies the method resolutionchain in Groovy

Meta Object Protocol

Devs can easily intercept any method call ( )Devs can react to calls to unexistent methods avoidingExceptions and providing default behaviour (great for

)Devs can even create new methods in RunTime!Take a look at

AOP

DSL's

GORM Dynamic Finders

Page 45: Introduccion a Groovy- Daniel Ortega

TEST IT OUT!class Test public String method() 'foo' new Test().method();

Execute

Page 46: Introduccion a Groovy- Daniel Ortega

TEST IT OUT!class Test public String method() 'foo' Test.metaClass.invokeMethod name, args ­> println "Called $name with $args" def method = delegate.class.metaClass.getMetaMethod( name, args ) if (method) println "Found Method" return method.invoke( delegate, args) else throw new UnsupportedOperationException("Wrong name!") new Test().method();

Execute

Page 47: Introduccion a Groovy- Daniel Ortega

TEST IT OUT!class Test public String method() 'foo' def methodMissing (String name, args) println 'Missing Called' def impl = new Random().nextInt(10) Test.metaClass[name] = impl impl() Test.metaClass.invokeMethod name, args ­> println "Called $name with $args" def method = delegate.class.metaClass.getMetaMethod( name, args ) if (method) println "Found Method" return method.invoke( delegate, args) else delegate.methodMissing(name, args) new Test().methodA();

Execute

Page 48: Introduccion a Groovy- Daniel Ortega

GROOVY AND DSL'SGroovy has extremely powerful capabilities for building

Create natural language API's for other devsYou can even transform your users into developers!

domain specific languages

Page 49: Introduccion a Groovy- Daniel Ortega

TEST IT OUT!import groovy.xml.*;new MarkupBuilder().root a( a1:'one' ) b 'test' c( a2:'two', 'blah' )

Execute

Page 50: Introduccion a Groovy- Daniel Ortega

BUILDING YOUR OWNnames = []def of, having, less = nulldef given(_the) [names: Object[] ns ­> names.addAll(ns) [and: n ­> names += n ] ]

def the = [ number: _of ­> [names: _having ­> [size: _less ­> [ than: println names.findAll it.size() < size.size() ]] ] , names : _having ­> [size: _less ­> [than: size ­> names.findAll it.size() < size.each println it ]] ], all = [ the: println names ], display = it

given the names "Ted", "Fred", "Jed" and "Ned"display all the namesdisplay the number of names having size less than 4display the names having size less than 4

Page 51: Introduccion a Groovy- Daniel Ortega

Q&A