SlideShare a Scribd company logo
1 of 34
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;
                                        }
Why do I care?
Why do I care?
Why do I care?
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?
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!

More Related Content

What's hot

Kotlin on Android: Delegate with pleasure
Kotlin on Android: Delegate with pleasureKotlin on Android: Delegate with pleasure
Kotlin on Android: Delegate with pleasureDmytro 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 ProgrammerMario 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 ExperienceAlexander 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 modelingMario 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 ReferenceSeung-Bum Lee
 
11. session 11 functions and objects
11. session 11   functions and objects11. session 11   functions and objects
11. session 11 functions and objectsPhúc Đỗ
 
(Greach 2015) Dsl'ing your Groovy
(Greach 2015) Dsl'ing your Groovy(Greach 2015) Dsl'ing your Groovy
(Greach 2015) Dsl'ing your GroovyAlonso 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 SwiftGiordano 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 APIMario Fusco
 
Brief Summary Of C++
Brief Summary Of C++Brief Summary Of C++
Brief Summary Of C++Haris Lye
 

What's hot (20)

ruby1_6up
ruby1_6upruby1_6up
ruby1_6up
 
Polyglot JVM
Polyglot JVMPolyglot JVM
Polyglot JVM
 
Kotlin on Android: Delegate with pleasure
Kotlin on Android: Delegate with pleasureKotlin on Android: Delegate with pleasure
Kotlin on Android: Delegate with pleasure
 
Scala 2013 review
Scala 2013 reviewScala 2013 review
Scala 2013 review
 
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
 
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
 
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
 
core.logic introduction
core.logic introductioncore.logic introduction
core.logic introduction
 
EMFPath
EMFPathEMFPath
EMFPath
 
Grails: a quick tutorial (1)
Grails: a quick tutorial (1)Grails: a quick tutorial (1)
Grails: a quick tutorial (1)
 
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
 
11. session 11 functions and objects
11. session 11   functions and objects11. session 11   functions and objects
11. session 11 functions and objects
 
(Greach 2015) Dsl'ing your Groovy
(Greach 2015) Dsl'ing your Groovy(Greach 2015) Dsl'ing your Groovy
(Greach 2015) Dsl'ing your Groovy
 
Hammurabi
HammurabiHammurabi
Hammurabi
 
Clojure And Swing
Clojure And SwingClojure And Swing
Clojure And Swing
 
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
 
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
 
Brief Summary Of C++
Brief Summary Of C++Brief Summary Of C++
Brief Summary Of C++
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScript
 

Similar to Groovy intro for OUDL

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 developersMatthew Farwell
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with ClojureDmitry 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 2017Sunghyouk Bae
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecLoï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 3Kirill 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
 

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
 
Introduction to Groovy
Introduction to GroovyIntroduction to Groovy
Introduction to Groovy
 
Groovy
GroovyGroovy
Groovy
 
Hw09 Hadoop + Clojure
Hw09   Hadoop + ClojureHw09   Hadoop + Clojure
Hw09 Hadoop + Clojure
 
Hadoop + Clojure
Hadoop + ClojureHadoop + Clojure
Hadoop + Clojure
 
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?
 
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
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)
 
Scala - en bedre Java?
Scala - en bedre Java?Scala - en bedre Java?
Scala - en bedre Java?
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
What's New In C# 7
What's New In C# 7What's New In C# 7
What's New In C# 7
 
Presentatie - Introductie in Groovy
Presentatie - Introductie in GroovyPresentatie - Introductie in Groovy
Presentatie - Introductie in Groovy
 
Kotlin @ Coupang Backend 2017
Kotlin @ Coupang Backend 2017Kotlin @ Coupang Backend 2017
Kotlin @ Coupang Backend 2017
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
 
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
 
SDC - Einführung in Scala
SDC - Einführung in ScalaSDC - Einführung in Scala
SDC - Einführung in Scala
 
Academy PRO: ES2015
Academy PRO: ES2015Academy PRO: ES2015
Academy PRO: ES2015
 
Jggug 2010 330 Grails 1.3 観察
Jggug 2010 330 Grails 1.3 観察Jggug 2010 330 Grails 1.3 観察
Jggug 2010 330 Grails 1.3 観察
 
Coding in Style
Coding in StyleCoding in Style
Coding in Style
 

Recently uploaded

Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Hyundai Motor Group
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 

Recently uploaded (20)

Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 

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; }
  • 17.
  • 18. Why do I care?
  • 19. Why do I care?
  • 20. Why do I care?
  • 21.
  • 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?
  • 27.
  • 28.
  • 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

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