Groovy And Grails Introduction

44
The Buzz About Groovy and Grails by Eric Weimer on March 10, 2009 The Chicago Groovy User Group Presented at

Transcript of Groovy And Grails Introduction

Page 1: Groovy And Grails Introduction

The Buzz About Groovy and Grails

by Eric Weimer

on March 10, 2009

The Chicago Groovy User Group

Presented at

Page 2: Groovy And Grails Introduction

• Eric B. Weimer

• 26 years developing software

• 10 years with Java stack

• Redpoint Technologies (sponsor)

• Roles

• Developer

• Independent consultant

• Application Architect

• Project/Program Manager

• Director Level

• Approach

• Fun and Agile

• “Life is a banquet”

Bio

Page 3: Groovy And Grails Introduction

Objectives

This talk is a presentation of my research. It will

answer the following questions:

• What is Groovy?

• What is Grails?

• What do they mean to Java developers?

• What do they mean to IT managers?

• Hidden secrets such as “how do I get first class

plane tickets for the price of coach?”

Page 4: Groovy And Grails Introduction

Groovy Defined

Groovy:

• Is a general purpose programming language

• Is a superset of Java syntax

• Fully Object-Orientated (no primitives!)

• Provides many “next generation” features from

Smalltalk, Python, Ruby and others.

• Designed to improve productivity

• Has become wildly popular

Page 5: Groovy And Grails Introduction

Grails Defined

Grails:

• Is a web application framework

• Is “full stack”

• Runs on Groovy

• One of many Groovy frameworks available

• Wildly popular

• Leverages Rails‟ Convention over Configuration

• Leverages Closures

Page 6: Groovy And Grails Introduction

Putting it all together

6

Groovy

Java Object Model

Java Virtual Machine

runs on

runs on

Page 7: Groovy And Grails Introduction

Putting it all together

7

Groovy

Bytecode

Java Virtual Machine

compiles to

runs on

Page 8: Groovy And Grails Introduction

Putting it all together

8

Grails (web

applications)

Groovy

Griffon (Swing

applications)

Frameworks

Page 9: Groovy And Grails Introduction

History of computing languages

The first programs looked like this:

0010 1101 0101 1100 0100 1011 0100 1010 1011 1100

0110 1110 0001 0000 0101 0011 0010 1111 0111 0011

0101 0011 0100 1111 0001 1000 0110 0101 1011 1100

0010 1101 0101 1100 0100 1011 0100 1010 0111 0011

0110 1110 0001 0000 0101 0011 0010 1111 1011 1100

0101 0011 0100 1111 0001 1000 0110 0101 0111 0011

0010 1101 0101 1100 0100 1011 0100 1010 1011 1100

0110 1110 0001 0000 0101 0011 0010 1111 0111 0011

0101 0011 0100 1111 0001 1000 0110 0101 1011 1100

0010 1101 0101 1100 0100 1011 0100 1010 0111 0011

0110 1110 0001 0000 0101 0011 0010 1111 1011 1100

0101 0011 0100 1111 0001 1000 0110 0101 0111 0011

Page 10: Groovy And Grails Introduction

Historical Documents

Page 11: Groovy And Grails Introduction

Early Russian Programmers

Page 12: Groovy And Grails Introduction

Programming was quite lucrative

Page 13: Groovy And Grails Introduction

How do I install Groovy and Grails

Easy:

• Download and unzip Groovy and Grails

• Set GROOVY_HOME, GRAILS_HOME

• Add %GROOVY_HOME%/bin to Path

• Add %GRAILS_HOME%/bin to Path

Optional:

• Install your IDE‟s Groovy plugin

Page 14: Groovy And Grails Introduction

Groovy Buzz Words

• Groovy Truth

• Duck Typing

• Syntactic Sugar

• Fully Object Orientated

• Closures

• Dynamic Objects

• Mixins

• Meta Object Protocol

• And more…

Page 15: Groovy And Grails Introduction

How Groovy handles boolean comparisons

•Groovy supports the standard conditional operators on boolean expressions

•In addition, Groovy has special rules for coercing non-boolean objects to a boolean value.

•Empty collections are false, non-empty are true.

•Empty maps are false, non-empty are true.

•Null object references are false, non-null are true.

•Non-zero numbers are true.

Groovy Truth

Page 16: Groovy And Grails Introduction

Examples:

def obj = null;

if ( obj ) …

obj = new Person()

if ( obj ) …

def numSnakes = 0

if ( numSnakes ) …

Groovy Truth

Page 17: Groovy And Grails Introduction

If it looks like a duck and quacks like a duck, …

def identity = new Identity()

identity = new Person()

identity = “Eric”

Duck Typing

Page 18: Groovy And Grails Introduction

Syntactic Sugar

•An alternative syntax

•More concise

•Improved clarity

•Improves productivity

•Syntactic sugar usually provides no additional functionality

Syntactic Sugar

Page 19: Groovy And Grails Introduction

// Semicolons are only required when necessary:

String friend = „Matt‟

// Parentheses are optional

println “eric has ${numDogs}‟s dogs”

// Except when the compiler cannot tell:

person.save(); children.save()

// return is optional

Syntactic Sugar

Page 20: Groovy And Grails Introduction

// Class variables are private by default in Groovy.

// Groovy generates the getters and setters for you:

class Person {

String firstName

String lastName

}

// In Groovy these are the same:

String firstName = p.getLastName( )

String firstName = p.lastName

Syntactic Sugar

Page 21: Groovy And Grails Introduction

// Groovy makes great use of the dot operator.

//

// Consider a web page. Groovy supports syntax for navigating

// hierarchical structures with Groovy Builders:

def page = DomBuilder( … )

// Get all the anchors in a page

List anchors = page.html.body.‟**‟.a

Syntactic Sugar

Page 22: Groovy And Grails Introduction

// Groovy supports the Java for loop:

for (int i = 0; i < 10; i++) { … }

// However a “sweeter” version of this is

(0..9).each { … }

// Or just

10.times { … }

Syntactic Sugar

Page 23: Groovy And Grails Introduction

// constructor sweetness

def person = new Person(

firstName: "Eric",

lastName: "Weimer",

address: new Address(

addressLine1: "101 Main Street",

city: "Lisle",

zipCode: "60532")

)

Syntactic Sugar

Page 24: Groovy And Grails Introduction

//Define an ArrayList:

def petList = [„Rocket‟,‟Portia‟,‟Cleo‟,‟Java‟]

// Define a HashMap

def employeeCellPhoneMap =

[Karl: „847-699-3222‟,

Emelye: „630-605-4355‟,

Natalie: „312-555-1234‟]

Syntactic Sugar

Page 25: Groovy And Grails Introduction

// Common Java bug

public boolean sameName (String aName) {

String name = “Matt”;

return name == aName;

}

boolean b = sameName(“Matt”);

Fully Object Orientated

Page 26: Groovy And Grails Introduction

Fully Object Orientated

Java primitives (int, short, long, double, char, etc.)

• In Java, operators only make sense for primitives

• What to do with comparison operators? (==, >, <, ...)

• Answer: Make them work for objects

• Via operator overloading!

• But isn‟t operator overloading a bad thing?

• Not unless it is abused…

• Groovy makes it intuitive

Page 27: Groovy And Grails Introduction

Groovy Comparison Operators

Operator Method

a == b a.equals(b)

a > b a.compareTo(b) > 0

a >= b a.compareTo(b) >= 0

a < b a.compareTo(b) < 0

a <= b a.compareTo(b) <= 0

Groovy Operators

Page 28: Groovy And Grails Introduction

Groovy Math-like operators

Operator Method

a + b a.plus(b)

a - b a.minus(b)

a * b a.multiply(b)

a / b a.divide(b)

a++ or ++a a.next()

a-- or --a a.previous()

a << b a.leftShift(b)

Array Operators

Operator Method

a[b] a.getAt(b)

a[b] = c a.putAt(b, c)

Groovy Math-like operators

Page 29: Groovy And Grails Introduction

public Boolean sameName (String aName) {

String name = “Stu”

name == aName

}

boolean b = sameName(“Stu”);

// Groovy version works as expected!

Fully Object Orientated

Page 30: Groovy And Grails Introduction

Closures

• A closure in Groovy is an object

• Java has syntax for strings: String x=“eric”;

• Groovy contains a syntax for closures

• In Groovy, a closure is defined by braces {…}

• As an object, you may assign it to a variable

• As an object, you may pass it to methods

• It can also reference any variables in scope

Page 31: Groovy And Grails Introduction

// A trivial example:

public void printList(List a) {

def pl = {println it}

a.each (pl)

}

Closures

Page 32: Groovy And Grails Introduction

class ItemController {

def save = { …

}

def search = { …

}

def get = {

}

}

Closures in Grails

Page 33: Groovy And Grails Introduction

• You can add methods and properties to classes

or objects.

• You can intercept method calls.

• Many examples such as tracking changes to a

POGO or POJO, logging, business rules, etc.

Dynamic Objects

Page 34: Groovy And Grails Introduction

Add methods to ANY class at runtime (even Java final).

// Assume you‟ve defined methods wordCount, charCount:

File.mixin WordCount, CharCount

Mixins

Page 35: Groovy And Grails Introduction

Metaprogramming

Metaclasses represent the runtime behavior of your classes and instances. Available per class and per instance.

ExpandoMetaClass DSL streamlines metaclass use.

Number.metaClass.multiply = { Amount amount -> amount.times(delegate) }

Meta Object Protocol

Page 36: Groovy And Grails Introduction

Metaprogramming

Metaclasses can add properties:

File.metaClass.getWordCount = {

delegate.text.split(/\w/).size()

}

new File('myFile.txt').wordCount

Meta Object Protocol

Page 37: Groovy And Grails Introduction

There is much more to Groovy

• Builders

• DSL

• Swing support (Griffon)

• Template framework

• Groovy Server Pages

• AST transformations

• Grape

• JMX Builder, OSGi support, etc. etc. etc.

Page 38: Groovy And Grails Introduction

Grails – what is it?

• Grails is a modern, full stack web application

framework in a box

• Grails is built in Spring and Hibernate

• Grails comes complete with a web server,

database, testing framework, automated build and

logging.

• Grails is not an RoR clone, it is inspired by Rails.

• Best demoed by example.

Page 39: Groovy And Grails Introduction

Grails – what is it?

• A full stack web framework built on Groovy

• Leverages proven industry standards like Spring

and Hibernate

• Supports “Convention over configuration” like Rails

• Makes use of closures like Rails

• Not designed to be a Groovy-based Rails, but

designed to be better than Rails

Page 40: Groovy And Grails Introduction

• Groovy is a scripting language

• Sun favors JRuby over Groovy

• Groovy is slow and full of bugs

• Java is sufficient for our needs

• Now that SpringSource has acquired Groovy,

and now that Spring favors paying customers,

does that mean Groovy is destined to be closed

source and require a fee?

Groovy Myths

Page 41: Groovy And Grails Introduction

Approval to use a new language can be difficult.

• Some shops require an elaborate process to

approve a new language.

• Hint: Begin with Groovy for unit testing

• Hint: Use Groovy for Ant scripting

• Present results of polls, statistics, etc. to show

Groovy has a large community of support

• Create a compelling argument for Groovy

adoption

• Emphasize productivity gains, competitive

advantage

Barriers to entry

Page 42: Groovy And Grails Introduction

In conclusion

How compelling are Groovy and Grails?

• Production ready

• Improves developer productivity

• Reduces bugs

• Eases migration for legacy Java developers

• Excellent documentation

• Community is growing geometrically

• Mainstream community awareness through

SpringSource

• Widespread anecdotal evidence of the claims above

• Lacks published metrics to support claims above

Page 43: Groovy And Grails Introduction

Recommended Reading

For beginners without Rails or Django experience:

Beginning Groovy and Grails: From Novice to Professional (Beginning from Novice to

Professional) by Christopher M. Judd, Joseph Faisal Nusairat, and Jim Shingler

Groovy and Grails Recipes (Recipes: a Problem-Solution Approach) by Bashar Abdul-Jawad

For the experienced:

Groovy in Action by Dierk Koenig, Andrew Glover, Paul King, and Guillaume Laforge

Programming Groovy: Dynamic Productivity for the Java Developer (Pragmatic

Programmers) by Venkat Subramaniam

Groovy Recipes: Greasing the Wheels of Java (Pragmatic Programmers) by Scott Davis

The Definitive Guide to Grails, Second Edition (Expert's Voice in Web Development) by

Graeme Rocher and Jeff Brown

Page 44: Groovy And Grails Introduction

In conclusion

You can find these slides on my blog at:

ericbweimer.blogspot.com

Thanks for coming!

Don‟t forget to stay for the prizes donated by Redpoint.