SlideShare a Scribd company logo
Intro to Groovy




 J. David Beutel

  2013-03-18
Presenter's Background
●   1991 Comp. Sci. BS from RIT
●   1996- using Java
●   2000- developing web apps in Java
●   2005- staff at UH ITS/MIS
●   2009- using Groovy
●   2010- app with Groovy/Grails/Geb/Spock
    –   in production since 2012 June
    –   LOC: 14K production, 13K test
Presentation Objectives

●   recognize and understand Groovy code
●   get interested in Groovy coding
●   (not introducing Spock/Geb/Grails yet)
Outline

●   What is Groovy?
●   Why do I care?
●   How is it different?
●   How can I use it?
What is Groovy?
●   dynamic extension of Java
    –   syntax
    –   API (GDK)
●   enables less code, more clarity
●   compiles to Java classes
●   seamless integration with Java
●   backed by SpringSource/VMware
●   good IDE support in
    –   IntelliJ IDEA (the best, IMHO)
    –   Eclipse Groovy/Grails (Spring) Tool Suite
Syntax
optional                                    literal
   ;                   String             'foo'
  ( )                  List               ['foo', 'bar']
                                                                              keyword
 public                Map                [name: 'David', age: 43]
                                                                                in
 return                Range              3..7
                                                                                as
                       regex Pattern      ~/d+/
 catch                                                                          def
                       multi-line         '''hello
 types
                       String             world'''

                 feature                                   example
       properties                   assert URL.'package'.name == 'java.net'
       Closure                      older = employees.findAll {it.age > 39}
       GString                      “$name was ${age - 1} years old last year”
       Groovy truth                 assert age
       yet another for loop         for (e in employees) {totalAge += e.age}
       named params                 e = new Employee(name: 'David', age: 43)
       multiple assignments         (first, last) = 'John Doe'.tokenize()
Syntax
         feature                                    example
default imports          java.io.*, java.lang.*, java.net.*, java.util.*
negative/range indexes   last = employees[-1]; allButLast = employees[0..-2]
dynamic properties       obj[propertyName]
dynamic methods          obj.”$methodName”(params)
meta-programming         Integer.metaClass.cos << {Math.cos(delegate)}
                         @InheritConstructors
AST transformations
                         class MyException extends Exception {}
                         assert 1 + 1 == 3
power assert                      |   |
                                  2   false
                         switch (age) {
                           case [41, 18, 32]:    yakudoshi(); break
                           case 0..17:           child(); break
power switch
                           case {it % 2}:        odd(); break
                           default:              even()
                         }
customizable operators                a+b                            a.plus(b)
Syntax
operator                                  meaning                       name
a ?: b      a?a:b                                               Elvis
a?.b        a == null ? a : a.b                                 null safe
m(*list)    m(list[0], list[1], ...)                            spread
list*.m()   [list[0].m(), list[1].m(), ...]                     spread-dot
list*.a                                                         spread-dot
            [list[0].a, list[1].a, ...]
list.a                                                          (GPath)
a.&m        reference to method m in object a as closure        method closure
a.@f        direct access to field f                            dot-at
t =~ s      Pattern.compile(s).matcher(t).find()                regex find
t ==~ s     Pattern.compile(s).matcher(t).matches()             regex match
a <=> b     a.compareTo(b) handling null                        spaceship
a == b      a.equals(b) handling null, coercion, & Comparable   equals
a.is(b)     like Java's a == b
API (GDK)
      method on Object                                       example
is(other)                        a.is(b), like Java's a == b
isCase(candidate)                for power switch and in, e.g., assert 2 in [1, 2, 3]
println(value)                   println 'hello world'
sleep(millis)                    sleep 1500
with(closure)                    employee.with {name = 'Joe'; age--}



  on Collection       returns                                  example
join(separator)     String        assert [1, 2, 3].join('|') == '1|2|3'
sort(closure)       List          youngestFirst = employees.sort {it.age}
sum()               Object        def totalAge = employees*.age.sum()
max(closure)        Object        assert ['hi', 'hello', 'hey'].max {it.length()} == 'hello'
flatten()           Collection    assert [1,[2,3],[[4]],[ ],5].flatten() == [1,2,3,4,5]
groupBy(closure) Map              assert [1,2,3,4,5].groupBy {it % 2} == [0:[2,4], 1:[1,3,5]]
API (GDK)

iterative method   returns                           example
findAll            List      older = employees.findAll {it.age > 39}
find               Object    firstOlder = employees.find {it.age > 39}
any                Boolean hasOlder = employees.any {it.age > 39}
every              Boolean noYounger = employees.every {it.age > 39}
                             def totalAge = 0
each               void
                             employees.each {totalAge += it.age}
                             employees.eachWithIndex { e, i ->
eachWithIndex      void        println “${e.name} is at index $i”
                             }
grep(classifier)   List      davids = employees*.name.grep ~/David.*/
collect            List      tripleAges = employees.collect {it.age * 3}
API (GDK)
            method on File          returns                          example
          eachFile(closure)       void          new File('somedir').eachFile {println it}
          getText()               String        pid = new File('app.pid').text.toLong()
          readLines()             List          lines = new File('grammar').readLines()
          eachLine(closure)       Object        file.eachLine {parse(it)}
                                  Object        new File('report').withWriter {out ->
          withWriter(closure)                     employees.each {it.write(out)}
                                                }


    on String           returns                                  example
split()               String[]     assert 'a b c'.split() == ['a', 'b', 'c']
tokenize(token)       List         assert '/tmp:/usr'.tokenize(':') == ['/tmp', '/usr']
normalize()           String       assert 'arnb'.normalize() == 'anb'
find(regex)           String       assert 'New York, NY 10292-0098'.find(/d{5}/) == '10292'
Why do I care?
Example: Exceptions

       C




Java
Java's journey
vers   year       feature                                         example
1.0    1996 initial release
                              HibernateTemplate hibernateTemplate = new HibernateTemplate(sessionFactory);
                              List products = (List) hibernateTemplate.execute(
                                 new HibernateCallback() {
                                    public Object doInHibernate(Session session) throws HibernateException {
              inner classes           return session.find(“FROM example.Product WHERE price > ?”,
                                                           new Integer(1000), Hibernate.INTEGER);
                                    }
                                 }
                              );
                              try {
                                 Class c = Class.forName("Foo");
                                 c.getMethod("hello").invoke(c.newInstance());

                              } catch (ClassNotFoundException e) {
1.1    1997                   }
                                 e.printStackTrace();

                              catch (InvocationTargetException e) {
                                 e.printStackTrace();
              reflection      }
                              catch (NoSuchMethodException e) {
                                 e.printStackTrace();
                              }
                              catch (InstantiationException e) {
                                 e.printStackTrace();
                              }
                              catch (IllegalAccessException e) {
                                 e.printStackTrace();
                              }

              other new API   JDBC, RMI
Java's journey
vers   year            feature                                     example
1.2    1998 Collections          List stooges = Arrays.asList(new String[] {“Larry”, “Moe”, “Curly”});

                                 Foo f = (Foo) Proxy.newProxyInstance(Foo.class.getClassLoader(),
              dynamic proxies                             new Class[] { Foo.class }, handler);
1.3    2000
              other new API      JNDI, JPDA
              assert             assert 1 + 1 == 2

1.4    2002 regex                assert Pattern.compile("d{5}").matcher("12345").matches();

              other new API      NIO, logging, XML, XSLT, JAXP, JCE, JSSE, JAAS
              generics           List<String> stooges = Arrays.asList(new String[] {"Larry", "Moe", "Curly"});

              annotations        @Override public String toString() { return “foo”; }

              enums              enum HolidayType {UH, STATE, BANK, FEDERAL}

1.5    2004 varargs              List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");

              autoboxing         List<Integer> ages = Arrays.asList(43, 35, 28);

              for each loop      for (String s : stooges) { System.out.println(s + " says "Nyuk nyuk.""); }

              static imports     import static org.apache.commons.lang.StringUtils.*;
Java's journey

vers    year           feature                                       example
                                        ScriptEngineManager factory = new ScriptEngineManager();
                                        ScriptEngine engine = factory.getEngineByName("JavaScript");
                                        try {
               scripting languages         engine.eval("print('Hello, World')");
1.6    2006                             } catch (ScriptException e) {
                                           e.printStackTrace();
                                        }

               other new API            JAX-WS (SOAP), JAXB
                                        switch(artistName) {
                                          case “Lily Allen”: return FABULOUS;
               Strings in switch          case “Elisa”:      return GREAT;
                                          default:           return MEH;
                                        }
1.7    2011    generic type inference   Map<String, List<String>> myMap = new HashMap<>();

                                        catch (IOException|SQLException ex) {
                                          logger.log(ex);
               catch multiple types       throw ex;
                                        }
Groovy intro for OUDL
Why do I care?
Why do I care?
Why do I care?
Groovy intro for OUDL
How is it different?

●   code comparison, Java versus Groovy
●   hello worlds
●   examples from my Timesheets project
How is it different?
How is it different?
How is it different?
How is it different?
Groovy intro for OUDL
Groovy intro for OUDL
How can I use it?


●   same as Java
●   scripts, e.g.
    –   groovy -e "println System.properties['user.home']"
    –   groovy -e 'println java.sql.Timestamp.valueOf("2012-11-17 06:49:33").time'
    –   web app stats polling daemon via JMX
●   JUnit -> Spock
●   Selenium -> Geb
●   Spring/Hibernate -> Grails
Usage: JUnit -> Spock
Usage: Selenium -> Geb
Usage: Spring/Hibernate -> Grails
For more about Groovy
●   groovy.codehaus.org
●   google, e.g., “groovy collection”
●   books
Let's make beautiful code!




   Thanks for coming!
Ad

More Related Content

What's hot (20)

ruby1_6up
ruby1_6upruby1_6up
ruby1_6up
tutorialsruby
 
Polyglot JVM
Polyglot JVMPolyglot JVM
Polyglot JVM
Arturo Herrero
 
Kotlin on Android: Delegate with pleasure
Kotlin on Android: Delegate with pleasureKotlin on Android: Delegate with pleasure
Kotlin on Android: Delegate with pleasure
Dmytro Zaitsev
 
Scala 2013 review
Scala 2013 reviewScala 2013 review
Scala 2013 review
Sagie Davidovich
 
OOP and FP - Become a Better Programmer
OOP and FP - Become a Better ProgrammerOOP and FP - Become a Better Programmer
OOP and FP - Become a Better Programmer
Mario Fusco
 
Scala for Java programmers
Scala for Java programmersScala for Java programmers
Scala for Java programmers
輝 子安
 
Declarative Internal DSLs in Lua: A Game Changing Experience
Declarative Internal DSLs in Lua: A Game Changing ExperienceDeclarative Internal DSLs in Lua: A Game Changing Experience
Declarative Internal DSLs in Lua: A Game Changing Experience
Alexander Gladysh
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
Mario Fusco
 
core.logic introduction
core.logic introductioncore.logic introduction
core.logic introduction
Norman Richards
 
EMFPath
EMFPathEMFPath
EMFPath
mikaelbarbero
 
Grails: a quick tutorial (1)
Grails: a quick tutorial (1)Grails: a quick tutorial (1)
Grails: a quick tutorial (1)
Davide Rossi
 
Martin Fowler's Refactoring Techniques Quick Reference
Martin Fowler's Refactoring Techniques Quick ReferenceMartin Fowler's Refactoring Techniques Quick Reference
Martin Fowler's Refactoring Techniques Quick Reference
Seung-Bum Lee
 
11. session 11 functions and objects
11. session 11   functions and objects11. session 11   functions and objects
11. session 11 functions and objects
Phúc Đỗ
 
(Greach 2015) Dsl'ing your Groovy
(Greach 2015) Dsl'ing your Groovy(Greach 2015) Dsl'ing your Groovy
(Greach 2015) Dsl'ing your Groovy
Alonso Torres
 
Hammurabi
HammurabiHammurabi
Hammurabi
Mario Fusco
 
Clojure And Swing
Clojure And SwingClojure And Swing
Clojure And Swing
Skills Matter
 
How to Clone Flappy Bird in Swift
How to Clone Flappy Bird in SwiftHow to Clone Flappy Bird in Swift
How to Clone Flappy Bird in Swift
Giordano Scalzo
 
Let's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java APILet's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java API
Mario Fusco
 
Brief Summary Of C++
Brief Summary Of C++Brief Summary Of C++
Brief Summary Of C++
Haris Lye
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScript
Scott Leberknight
 
Kotlin on Android: Delegate with pleasure
Kotlin on Android: Delegate with pleasureKotlin on Android: Delegate with pleasure
Kotlin on Android: Delegate with pleasure
Dmytro Zaitsev
 
OOP and FP - Become a Better Programmer
OOP and FP - Become a Better ProgrammerOOP and FP - Become a Better Programmer
OOP and FP - Become a Better Programmer
Mario Fusco
 
Scala for Java programmers
Scala for Java programmersScala for Java programmers
Scala for Java programmers
輝 子安
 
Declarative Internal DSLs in Lua: A Game Changing Experience
Declarative Internal DSLs in Lua: A Game Changing ExperienceDeclarative Internal DSLs in Lua: A Game Changing Experience
Declarative Internal DSLs in Lua: A Game Changing Experience
Alexander Gladysh
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
Mario Fusco
 
Grails: a quick tutorial (1)
Grails: a quick tutorial (1)Grails: a quick tutorial (1)
Grails: a quick tutorial (1)
Davide Rossi
 
Martin Fowler's Refactoring Techniques Quick Reference
Martin Fowler's Refactoring Techniques Quick ReferenceMartin Fowler's Refactoring Techniques Quick Reference
Martin Fowler's Refactoring Techniques Quick Reference
Seung-Bum Lee
 
11. session 11 functions and objects
11. session 11   functions and objects11. session 11   functions and objects
11. session 11 functions and objects
Phúc Đỗ
 
(Greach 2015) Dsl'ing your Groovy
(Greach 2015) Dsl'ing your Groovy(Greach 2015) Dsl'ing your Groovy
(Greach 2015) Dsl'ing your Groovy
Alonso Torres
 
How to Clone Flappy Bird in Swift
How to Clone Flappy Bird in SwiftHow to Clone Flappy Bird in Swift
How to Clone Flappy Bird in Swift
Giordano Scalzo
 
Let's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java APILet's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java API
Mario Fusco
 
Brief Summary Of C++
Brief Summary Of C++Brief Summary Of C++
Brief Summary Of C++
Haris Lye
 

Similar to Groovy intro for OUDL (20)

The Future of JVM Languages
The Future of JVM Languages The Future of JVM Languages
The Future of JVM Languages
VictorSzoltysek
 
Introduction to Groovy
Introduction to GroovyIntroduction to Groovy
Introduction to Groovy
André Faria Gomes
 
Groovy
GroovyGroovy
Groovy
Zen Urban
 
Hw09 Hadoop + Clojure
Hw09   Hadoop + ClojureHw09   Hadoop + Clojure
Hw09 Hadoop + Clojure
Cloudera, Inc.
 
Hadoop + Clojure
Hadoop + ClojureHadoop + Clojure
Hadoop + Clojure
elliando dias
 
Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?
Jesper Kamstrup Linnet
 
Softshake 2013: 10 reasons why java developers are jealous of Scala developers
Softshake 2013: 10 reasons why java developers are jealous of Scala developersSoftshake 2013: 10 reasons why java developers are jealous of Scala developers
Softshake 2013: 10 reasons why java developers are jealous of Scala developers
Matthew Farwell
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
Dmitry Buzdin
 
Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)
HamletDRC
 
Scala - en bedre Java?
Scala - en bedre Java?Scala - en bedre Java?
Scala - en bedre Java?
Jesper Kamstrup Linnet
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
Lorenzo Dematté
 
What's New In C# 7
What's New In C# 7What's New In C# 7
What's New In C# 7
Paulo Morgado
 
Presentatie - Introductie in Groovy
Presentatie - Introductie in GroovyPresentatie - Introductie in Groovy
Presentatie - Introductie in Groovy
Getting value from IoT, Integration and Data Analytics
 
Kotlin @ Coupang Backend 2017
Kotlin @ Coupang Backend 2017Kotlin @ Coupang Backend 2017
Kotlin @ Coupang Backend 2017
Sunghyouk Bae
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
Loïc Descotte
 
Kotlin Advanced - Apalon Kotlin Sprint Part 3
Kotlin Advanced - Apalon Kotlin Sprint Part 3Kotlin Advanced - Apalon Kotlin Sprint Part 3
Kotlin Advanced - Apalon Kotlin Sprint Part 3
Kirill Rozov
 
SDC - Einführung in Scala
SDC - Einführung in ScalaSDC - Einführung in Scala
SDC - Einführung in Scala
Christian Baranowski
 
Academy PRO: ES2015
Academy PRO: ES2015Academy PRO: ES2015
Academy PRO: ES2015
Binary Studio
 
Jggug 2010 330 Grails 1.3 観察
Jggug 2010 330 Grails 1.3 観察Jggug 2010 330 Grails 1.3 観察
Jggug 2010 330 Grails 1.3 観察
Tsuyoshi Yamamoto
 
Coding in Style
Coding in StyleCoding in Style
Coding in Style
scalaconfjp
 
The Future of JVM Languages
The Future of JVM Languages The Future of JVM Languages
The Future of JVM Languages
VictorSzoltysek
 
Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?
Jesper Kamstrup Linnet
 
Softshake 2013: 10 reasons why java developers are jealous of Scala developers
Softshake 2013: 10 reasons why java developers are jealous of Scala developersSoftshake 2013: 10 reasons why java developers are jealous of Scala developers
Softshake 2013: 10 reasons why java developers are jealous of Scala developers
Matthew Farwell
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
Dmitry Buzdin
 
Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)
HamletDRC
 
Kotlin @ Coupang Backend 2017
Kotlin @ Coupang Backend 2017Kotlin @ Coupang Backend 2017
Kotlin @ Coupang Backend 2017
Sunghyouk Bae
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
Loïc Descotte
 
Kotlin Advanced - Apalon Kotlin Sprint Part 3
Kotlin Advanced - Apalon Kotlin Sprint Part 3Kotlin Advanced - Apalon Kotlin Sprint Part 3
Kotlin Advanced - Apalon Kotlin Sprint Part 3
Kirill Rozov
 
Jggug 2010 330 Grails 1.3 観察
Jggug 2010 330 Grails 1.3 観察Jggug 2010 330 Grails 1.3 観察
Jggug 2010 330 Grails 1.3 観察
Tsuyoshi Yamamoto
 
Ad

Recently uploaded (20)

Top 5 Qualities to Look for in Salesforce Partners in 2025
Top 5 Qualities to Look for in Salesforce Partners in 2025Top 5 Qualities to Look for in Salesforce Partners in 2025
Top 5 Qualities to Look for in Salesforce Partners in 2025
Damco Salesforce Services
 
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Safe Software
 
Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?
Eric Torreborre
 
AI-proof your career by Olivier Vroom and David WIlliamson
AI-proof your career by Olivier Vroom and David WIlliamsonAI-proof your career by Olivier Vroom and David WIlliamson
AI-proof your career by Olivier Vroom and David WIlliamson
UXPA Boston
 
論文紹介:"InfLoRA: Interference-Free Low-Rank Adaptation for Continual Learning" ...
論文紹介:"InfLoRA: Interference-Free Low-Rank Adaptation for Continual Learning" ...論文紹介:"InfLoRA: Interference-Free Low-Rank Adaptation for Continual Learning" ...
論文紹介:"InfLoRA: Interference-Free Low-Rank Adaptation for Continual Learning" ...
Toru Tamaki
 
OpenAI Just Announced Codex: A cloud engineering agent that excels in handlin...
OpenAI Just Announced Codex: A cloud engineering agent that excels in handlin...OpenAI Just Announced Codex: A cloud engineering agent that excels in handlin...
OpenAI Just Announced Codex: A cloud engineering agent that excels in handlin...
SOFTTECHHUB
 
Cybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and MitigationCybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and Mitigation
VICTOR MAESTRE RAMIREZ
 
May Patch Tuesday
May Patch TuesdayMay Patch Tuesday
May Patch Tuesday
Ivanti
 
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdfKit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Wonjun Hwang
 
Multi-Agent AI Systems: Architectures & Communication (MCP and A2A)
Multi-Agent AI Systems: Architectures & Communication (MCP and A2A)Multi-Agent AI Systems: Architectures & Communication (MCP and A2A)
Multi-Agent AI Systems: Architectures & Communication (MCP and A2A)
HusseinMalikMammadli
 
Best 10 Free AI Character Chat Platforms
Best 10 Free AI Character Chat PlatformsBest 10 Free AI Character Chat Platforms
Best 10 Free AI Character Chat Platforms
Soulmaite
 
Agentic Automation - Delhi UiPath Community Meetup
Agentic Automation - Delhi UiPath Community MeetupAgentic Automation - Delhi UiPath Community Meetup
Agentic Automation - Delhi UiPath Community Meetup
Manoj Batra (1600 + Connections)
 
DevOpsDays SLC - Platform Engineers are Product Managers.pptx
DevOpsDays SLC - Platform Engineers are Product Managers.pptxDevOpsDays SLC - Platform Engineers are Product Managers.pptx
DevOpsDays SLC - Platform Engineers are Product Managers.pptx
Justin Reock
 
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Maarten Verwaest
 
Build With AI - In Person Session Slides.pdf
Build With AI - In Person Session Slides.pdfBuild With AI - In Person Session Slides.pdf
Build With AI - In Person Session Slides.pdf
Google Developer Group - Harare
 
Computer Systems Quiz Presentation in Purple Bold Style (4).pdf
Computer Systems Quiz Presentation in Purple Bold Style (4).pdfComputer Systems Quiz Presentation in Purple Bold Style (4).pdf
Computer Systems Quiz Presentation in Purple Bold Style (4).pdf
fizarcse
 
UiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptx
UiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptxUiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptx
UiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptx
anabulhac
 
Who's choice? Making decisions with and about Artificial Intelligence, Keele ...
Who's choice? Making decisions with and about Artificial Intelligence, Keele ...Who's choice? Making decisions with and about Artificial Intelligence, Keele ...
Who's choice? Making decisions with and about Artificial Intelligence, Keele ...
Alan Dix
 
Building the Customer Identity Community, Together.pdf
Building the Customer Identity Community, Together.pdfBuilding the Customer Identity Community, Together.pdf
Building the Customer Identity Community, Together.pdf
Cheryl Hung
 
accessibility Considerations during Design by Rick Blair, Schneider Electric
accessibility Considerations during Design by Rick Blair, Schneider Electricaccessibility Considerations during Design by Rick Blair, Schneider Electric
accessibility Considerations during Design by Rick Blair, Schneider Electric
UXPA Boston
 
Top 5 Qualities to Look for in Salesforce Partners in 2025
Top 5 Qualities to Look for in Salesforce Partners in 2025Top 5 Qualities to Look for in Salesforce Partners in 2025
Top 5 Qualities to Look for in Salesforce Partners in 2025
Damco Salesforce Services
 
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Safe Software
 
Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?
Eric Torreborre
 
AI-proof your career by Olivier Vroom and David WIlliamson
AI-proof your career by Olivier Vroom and David WIlliamsonAI-proof your career by Olivier Vroom and David WIlliamson
AI-proof your career by Olivier Vroom and David WIlliamson
UXPA Boston
 
論文紹介:"InfLoRA: Interference-Free Low-Rank Adaptation for Continual Learning" ...
論文紹介:"InfLoRA: Interference-Free Low-Rank Adaptation for Continual Learning" ...論文紹介:"InfLoRA: Interference-Free Low-Rank Adaptation for Continual Learning" ...
論文紹介:"InfLoRA: Interference-Free Low-Rank Adaptation for Continual Learning" ...
Toru Tamaki
 
OpenAI Just Announced Codex: A cloud engineering agent that excels in handlin...
OpenAI Just Announced Codex: A cloud engineering agent that excels in handlin...OpenAI Just Announced Codex: A cloud engineering agent that excels in handlin...
OpenAI Just Announced Codex: A cloud engineering agent that excels in handlin...
SOFTTECHHUB
 
Cybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and MitigationCybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and Mitigation
VICTOR MAESTRE RAMIREZ
 
May Patch Tuesday
May Patch TuesdayMay Patch Tuesday
May Patch Tuesday
Ivanti
 
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdfKit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Wonjun Hwang
 
Multi-Agent AI Systems: Architectures & Communication (MCP and A2A)
Multi-Agent AI Systems: Architectures & Communication (MCP and A2A)Multi-Agent AI Systems: Architectures & Communication (MCP and A2A)
Multi-Agent AI Systems: Architectures & Communication (MCP and A2A)
HusseinMalikMammadli
 
Best 10 Free AI Character Chat Platforms
Best 10 Free AI Character Chat PlatformsBest 10 Free AI Character Chat Platforms
Best 10 Free AI Character Chat Platforms
Soulmaite
 
DevOpsDays SLC - Platform Engineers are Product Managers.pptx
DevOpsDays SLC - Platform Engineers are Product Managers.pptxDevOpsDays SLC - Platform Engineers are Product Managers.pptx
DevOpsDays SLC - Platform Engineers are Product Managers.pptx
Justin Reock
 
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Maarten Verwaest
 
Computer Systems Quiz Presentation in Purple Bold Style (4).pdf
Computer Systems Quiz Presentation in Purple Bold Style (4).pdfComputer Systems Quiz Presentation in Purple Bold Style (4).pdf
Computer Systems Quiz Presentation in Purple Bold Style (4).pdf
fizarcse
 
UiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptx
UiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptxUiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptx
UiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptx
anabulhac
 
Who's choice? Making decisions with and about Artificial Intelligence, Keele ...
Who's choice? Making decisions with and about Artificial Intelligence, Keele ...Who's choice? Making decisions with and about Artificial Intelligence, Keele ...
Who's choice? Making decisions with and about Artificial Intelligence, Keele ...
Alan Dix
 
Building the Customer Identity Community, Together.pdf
Building the Customer Identity Community, Together.pdfBuilding the Customer Identity Community, Together.pdf
Building the Customer Identity Community, Together.pdf
Cheryl Hung
 
accessibility Considerations during Design by Rick Blair, Schneider Electric
accessibility Considerations during Design by Rick Blair, Schneider Electricaccessibility Considerations during Design by Rick Blair, Schneider Electric
accessibility Considerations during Design by Rick Blair, Schneider Electric
UXPA Boston
 
Ad

Groovy intro for OUDL

  • 1. Intro to Groovy J. David Beutel 2013-03-18
  • 2. Presenter's Background ● 1991 Comp. Sci. BS from RIT ● 1996- using Java ● 2000- developing web apps in Java ● 2005- staff at UH ITS/MIS ● 2009- using Groovy ● 2010- app with Groovy/Grails/Geb/Spock – in production since 2012 June – LOC: 14K production, 13K test
  • 3. Presentation Objectives ● recognize and understand Groovy code ● get interested in Groovy coding ● (not introducing Spock/Geb/Grails yet)
  • 4. Outline ● What is Groovy? ● Why do I care? ● How is it different? ● How can I use it?
  • 5. What is Groovy? ● dynamic extension of Java – syntax – API (GDK) ● enables less code, more clarity ● compiles to Java classes ● seamless integration with Java ● backed by SpringSource/VMware ● good IDE support in – IntelliJ IDEA (the best, IMHO) – Eclipse Groovy/Grails (Spring) Tool Suite
  • 6. Syntax optional literal ; String 'foo' ( ) List ['foo', 'bar'] keyword public Map [name: 'David', age: 43] in return Range 3..7 as regex Pattern ~/d+/ catch def multi-line '''hello types String world''' feature example properties assert URL.'package'.name == 'java.net' Closure older = employees.findAll {it.age > 39} GString “$name was ${age - 1} years old last year” Groovy truth assert age yet another for loop for (e in employees) {totalAge += e.age} named params e = new Employee(name: 'David', age: 43) multiple assignments (first, last) = 'John Doe'.tokenize()
  • 7. Syntax feature example default imports java.io.*, java.lang.*, java.net.*, java.util.* negative/range indexes last = employees[-1]; allButLast = employees[0..-2] dynamic properties obj[propertyName] dynamic methods obj.”$methodName”(params) meta-programming Integer.metaClass.cos << {Math.cos(delegate)} @InheritConstructors AST transformations class MyException extends Exception {} assert 1 + 1 == 3 power assert | | 2 false switch (age) { case [41, 18, 32]: yakudoshi(); break case 0..17: child(); break power switch case {it % 2}: odd(); break default: even() } customizable operators a+b a.plus(b)
  • 8. Syntax operator meaning name a ?: b a?a:b Elvis a?.b a == null ? a : a.b null safe m(*list) m(list[0], list[1], ...) spread list*.m() [list[0].m(), list[1].m(), ...] spread-dot list*.a spread-dot [list[0].a, list[1].a, ...] list.a (GPath) a.&m reference to method m in object a as closure method closure a.@f direct access to field f dot-at t =~ s Pattern.compile(s).matcher(t).find() regex find t ==~ s Pattern.compile(s).matcher(t).matches() regex match a <=> b a.compareTo(b) handling null spaceship a == b a.equals(b) handling null, coercion, & Comparable equals a.is(b) like Java's a == b
  • 9. API (GDK) method on Object example is(other) a.is(b), like Java's a == b isCase(candidate) for power switch and in, e.g., assert 2 in [1, 2, 3] println(value) println 'hello world' sleep(millis) sleep 1500 with(closure) employee.with {name = 'Joe'; age--} on Collection returns example join(separator) String assert [1, 2, 3].join('|') == '1|2|3' sort(closure) List youngestFirst = employees.sort {it.age} sum() Object def totalAge = employees*.age.sum() max(closure) Object assert ['hi', 'hello', 'hey'].max {it.length()} == 'hello' flatten() Collection assert [1,[2,3],[[4]],[ ],5].flatten() == [1,2,3,4,5] groupBy(closure) Map assert [1,2,3,4,5].groupBy {it % 2} == [0:[2,4], 1:[1,3,5]]
  • 10. API (GDK) iterative method returns example findAll List older = employees.findAll {it.age > 39} find Object firstOlder = employees.find {it.age > 39} any Boolean hasOlder = employees.any {it.age > 39} every Boolean noYounger = employees.every {it.age > 39} def totalAge = 0 each void employees.each {totalAge += it.age} employees.eachWithIndex { e, i -> eachWithIndex void println “${e.name} is at index $i” } grep(classifier) List davids = employees*.name.grep ~/David.*/ collect List tripleAges = employees.collect {it.age * 3}
  • 11. API (GDK) method on File returns example eachFile(closure) void new File('somedir').eachFile {println it} getText() String pid = new File('app.pid').text.toLong() readLines() List lines = new File('grammar').readLines() eachLine(closure) Object file.eachLine {parse(it)} Object new File('report').withWriter {out -> withWriter(closure) employees.each {it.write(out)} } on String returns example split() String[] assert 'a b c'.split() == ['a', 'b', 'c'] tokenize(token) List assert '/tmp:/usr'.tokenize(':') == ['/tmp', '/usr'] normalize() String assert 'arnb'.normalize() == 'anb' find(regex) String assert 'New York, NY 10292-0098'.find(/d{5}/) == '10292'
  • 12. Why do I care?
  • 14. Java's journey vers year feature example 1.0 1996 initial release HibernateTemplate hibernateTemplate = new HibernateTemplate(sessionFactory); List products = (List) hibernateTemplate.execute( new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException { inner classes return session.find(“FROM example.Product WHERE price > ?”, new Integer(1000), Hibernate.INTEGER); } } ); try { Class c = Class.forName("Foo"); c.getMethod("hello").invoke(c.newInstance()); } catch (ClassNotFoundException e) { 1.1 1997 } e.printStackTrace(); catch (InvocationTargetException e) { e.printStackTrace(); reflection } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } other new API JDBC, RMI
  • 15. Java's journey vers year feature example 1.2 1998 Collections List stooges = Arrays.asList(new String[] {“Larry”, “Moe”, “Curly”}); Foo f = (Foo) Proxy.newProxyInstance(Foo.class.getClassLoader(), dynamic proxies new Class[] { Foo.class }, handler); 1.3 2000 other new API JNDI, JPDA assert assert 1 + 1 == 2 1.4 2002 regex assert Pattern.compile("d{5}").matcher("12345").matches(); other new API NIO, logging, XML, XSLT, JAXP, JCE, JSSE, JAAS generics List<String> stooges = Arrays.asList(new String[] {"Larry", "Moe", "Curly"}); annotations @Override public String toString() { return “foo”; } enums enum HolidayType {UH, STATE, BANK, FEDERAL} 1.5 2004 varargs List<String> stooges = Arrays.asList("Larry", "Moe", "Curly"); autoboxing List<Integer> ages = Arrays.asList(43, 35, 28); for each loop for (String s : stooges) { System.out.println(s + " says "Nyuk nyuk.""); } static imports import static org.apache.commons.lang.StringUtils.*;
  • 16. Java's journey vers year feature example ScriptEngineManager factory = new ScriptEngineManager(); ScriptEngine engine = factory.getEngineByName("JavaScript"); try { scripting languages engine.eval("print('Hello, World')"); 1.6 2006 } catch (ScriptException e) { e.printStackTrace(); } other new API JAX-WS (SOAP), JAXB switch(artistName) { case “Lily Allen”: return FABULOUS; Strings in switch case “Elisa”: return GREAT; default: return MEH; } 1.7 2011 generic type inference Map<String, List<String>> myMap = new HashMap<>(); catch (IOException|SQLException ex) { logger.log(ex); catch multiple types throw ex; }
  • 18. Why do I care?
  • 19. Why do I care?
  • 20. Why do I care?
  • 22. How is it different? ● code comparison, Java versus Groovy ● hello worlds ● examples from my Timesheets project
  • 23. How is it different?
  • 24. How is it different?
  • 25. How is it different?
  • 26. How is it different?
  • 29. How can I use it? ● same as Java ● scripts, e.g. – groovy -e "println System.properties['user.home']" – groovy -e 'println java.sql.Timestamp.valueOf("2012-11-17 06:49:33").time' – web app stats polling daemon via JMX ● JUnit -> Spock ● Selenium -> Geb ● Spring/Hibernate -> Grails
  • 33. For more about Groovy ● groovy.codehaus.org ● google, e.g., “groovy collection” ● books
  • 34. Let's make beautiful code! Thanks for coming!

Editor's Notes

  • #13: My 1 st job after college was programming client/server apps in C and X Windows on Unix, for 6 years. Java was released towards the end, and I loved its exceptions, safe memory, garbage collection, and simpler API. Memory management and error handling in C took so much time programming around and debugging, while Java did it automatically or more cleanly, that I couldn&apos;t stand C anymore. For example, compare error handling in C with Exceptions in Java...
  翻译: