introduccion a groovy- daniel ortega

Post on 14-Apr-2017

538 Views

Category:

Technology

5 Downloads

Preview:

Click to see full reader

TRANSCRIPT

GROOVY INTRODUCTIONWAY MORE THAN JAVA WITHOUT

SEMICOLONS

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

EAT MEAT

ABOUT THISPRESENTATION

FrontEnd Backend

Slideshow Powered

Source code available at Live at (at leasttoday)

SPAAngularJSGrailsReveal.jsGroovy

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

WHAT IS GROOVY?

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

the 21st century"

Scott Davis

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

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

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

We all are Groovy devs!

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)

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

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());

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())

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())

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())

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()

JAVA TO GROOVYTHE GROOVY WAY!

class GroovyExample String variable

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

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

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());

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

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

Execute

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); );

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 ...

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

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

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

GROOVY OPERATORSGroovy supports all Java regular operators

ArithmeticUnaryRelationalLogicalBitwiseTernary Operator

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

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'

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

GROOVY SPECIAL OPERATORSSPACESHIFT OPERATOR <=>

Shortcut for compareTo() calls

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

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'

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']

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'

GROOVY SPECIAL OPERATORSMETHOD OPERATOR .&

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

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

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);

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

Collections APIFile API

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]

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

WHERE ARE THE BUFFERED READERS AND THETRY/CATCH STATEMENTS?

NEITHER CHECKED NOR UNCHECKED EXCEPTIONS NEED TO BECAUGHT

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

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

Execute

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

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

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

Execute

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

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

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

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

Execute

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

Q&A

top related