Welcome to my Groovy Learning Made Easy post.
It is always worth to be a polyglot learner and programmer. If you are a java developer, then why not to learn
another programming language called Groovy. This post will provide you the
getting started directions with sample code snippet for learning Groovy.
Why Java developer should
learn another programming language, so called Groovy?
- Languages other than Java that run on the JVM are called as alternative JVM Languages. For example - Groovy, Scala, Clojure, Jruby, Jython… Among those, Groovy is the most accessible alternative JVM language to Java developers.
- As per polyglot programming pyramid by Ola Bini, Java can fit in static layer but it isn’t ideal language for solving problems in the dynamic layer. These problems include rapid web development, prototyping, scripting, and more. Groovy is designed to solve exactly such problems, though there are also other programming languages capable to solve such problems like Ruby, Clojure, etc.
- Groovy is well-suited for writing domain-specific language (DSL). For example - Gradle build tool is written in Java and Groovy, and introduces a Groovy-based DSL instead of the more traditional XML form of declaring the project configuration.
- The Groovy programming language is supported by Pivotal and the Groovy Community, so we can expect good community support. Also Groovy roadmap has the considerations of supporting new Java releases, for example JDK-8 support is targeted to include in Groovy 3.0 by Q4 2014.
- Excellent interoperability between Groovy and Java. So the best thing is you can use your existing Java libraries in Groovy code. Basically Groovy extends java.lang.Object and adding some functional behavior. At the end, Groovy source code compiles to JVM bytecode.
- Inspired by Smalltalk, Ruby, and Python, Groovy has implemented several language features that Java doesn't, such as: Function literals / Closures, First-class support for collections, First-class support for regular expressions, First-class support for XML processing (First-class support = that is built into the language syntax as opposed to requiring library calls)
- Like Java, there are many Groovy based frameworks available. For example - Grails for web application development, Spock for writing acceptance tests, etc.
- Groovy enjoys rich IDE support / Eclipse based Groovy/Grails tools suite, so Java developers don't need to learn new development tooling.
About Groovy…
Pasted from <http://groovy.codehaus.org/>
- is an agile and dynamic language for the Java Virtual Machine
- builds upon the strengths of Java but has additional power features inspired by languages like Python, Ruby and Smalltalk
- makes modern programming features available to Java developers with almost-zero learning curve
- provides the ability to statically type check and statically compile your code for robustness and performance
- supports Domain-Specific Languages and other compact syntax so your code becomes easy to read and maintain
- makes writing shell and build scripts easy with its powerful processing primitives, OO abilities and an Ant DSL
- increases developer productivity by reducing scaffolding code when developing web, GUI, database or console applications
- simplifies testing by supporting unit testing and mocking out-of-the-box
- seamlessly integrates with all existing Java classes and libraries
- compiles straight to Java bytecode so you can use it anywhere you can use Java
Getting Started Guide to
Learn Groovy
I recommend to
follow steps in below sequence to getting started with Groovy quickly.
Step-1: Groovy environment
setup
If you are java
developer, then installing Groovy is all about just spending less than 15
minutes after downloading Groovy - http://groovy.codehaus.org/Installing+Groovy
If you already have
Eclipse, let's install Groovy
plugin in Eclipse. Alternatively you may consider GGST (Groovy/Grails Tool Suite).
Step-2: Groovy project setup
Download and setup
my "GroovyQuickStart" project, because that would enable you to learn
Groovy quickly using sample code snippet.
- Download zip file of / Clone project to your local machine.
- Then just import "GroovyQuickStart" project in Eclipse having Groovy plugins already installed.
- Fix all build path errors (Project -> Properties -> Java Build Path -> Libraries), such as JRE configuration, Groovy Libraries, etc.
- Now run "G00_BasicConcepts.groovy" groovy script files with Groovy Script option (Alt + Shift + X, G) in Eclipse and you should be able to see output in console without any error. That's it.
- As directed in next steps, let's start exploring each package containing code of ".groovy" files in given sequence of G00, G01*, G02*...
Step-3: Learning Basic
concepts and syntax
Groovy eliminates
much of Java's verbosity. It has advanced collection handling, supports
functional concepts and brings dynamic typing to the JVM. By default Groovy
imports the list of packages and hence those are always implicitly available
for access in your Groovy code: groovy.lang.*, groovy.util.*, java.lang.*,
java.io.*, java.math.BigDecimal, java.math.BigInteger, java.net.*, java.util.*.
In the downloaded
"GroovyQuickStart" project, explore com.tirthal.learning.basic
package for learning basic concepts and syntax of Groovy as well as features
like Collections, Ranges, Functions, Closures...
Step-4: Working with XML in
Groovy
All of Java's native
XML processing options are available to access in Groovy, but Groovy brings new
options for both low and high level processing of XML. Reading and writing of
XML is made easier due to Groovy's dynamicity.
Groovy offers
First-class XML processing. In the downloaded "GroovyQuickStart"
project, explore com.tirthal.learning.xml
package to realize how easy it is to read and write XML in Groovy. Also refer
sample xml files in data folder of the project.
Reading XML
- DomCategory - Low level access to Java's DOM API
- XmlParser - High level API for DOM process, but entire document is loaded in memory. Eager evaluation. So prohibited for processing larger documents
- XmlSlurper - Very similar to XmlParser, but using lazy evaluation. This means that only portion loaded into memory just before they read. Ideal when need to access subset of content in the XML.
Writing XML
- MarkupBuilder - Simple XML creation API
- StreamingMarkupBuilder - Advanced XML creation and provides better support for creating large documents
Step-5: Groovy and Java
interoperability
In the downloaded
"GroovyQuickStart" project, explore com.tirthal.learning.interoperability
package to understand how flexible it is to call Java from Groovy and
vice-versa.
Calling
Java from Groovy
- Groovy works with existing Java libraries - Including popular libraries such as Google Guava or Apache Commons or your own proprietary libraries
- If you intend your Groovy code to interoperate with Java, it can pay to use static types where possible, because it simplifies type overloading and dispatch
- Use Grape for dependency management in Groovy. It is natively supported in Groovy language and build on Ivy.
Calling
Groovy from Java
- Calling Groovy from inside a Java application requires the Groovy JAR and other related JARs to be put into your Java application’s CLASSPATH, as they’re runtime dependencies.
- Simply put the GROOVY_HOME/embeddable/groovy-all-x.jar file into your CLASSPATH.
- There are several ways you can call Groovy code from inside a Java application:
- Using the Bean Scripting Framework (BSF)—a.k.a. JSR 223
- Using GroovyShell
- Using GroovyClassLoader
- Using GroovyScriptEngine
- Using the embedded Groovy console
- The most commonly used ways are - Groovy-ClassLoader and GroovyScriptEngine.
Step-6: Working with REST
services
In the downloaded
"GroovyQuickStart" project, explore com.tirthal.learning.rest
package to know that how Groovy is well-suited working with REST services and
JSON.
- RestClient - encapsulates HTTP requests and responses
- Groovy ConfigSlurper - for reading configuration file
Step-7: Unit testing in
Groovy
Unit testing becomes
vary important when working with dynamic languages, because the compiler
doesn't enforce type-checking. In the downloaded "GroovyQuickStart"
project, explore com.tirthal.learning.testing
package to experience unit testing support in Groovy.
- JUnit is built directly into the Groovy runtime
- Mocking APIs are included in the Groovy platform
- Advanced testing frameworks are also available
Step-8: Miscellaneous
Based on your
interest and need, you can explore it further.
- Groovy 2.0 introduces static compilation for Groovy - The newly released Groovy 2.0 brings key static features to the language with static type checking and static compilation, adopts JDK 7 related improvements with Project Coin syntax enhancements and the support of the new "invoke dynamic" JVM instruction, and becomes more modular than before.
- Groovy 2.3 Introduces Traits - A trait is a reusable set of methods and fields that can be added to one or more classes. A class can be composed out of multiple traits without using multiple inheritance (and therefore avoiding the diamond problem).
- Refer detailed Groovy documentation.
- For Spring developers, Spring 4 has a full support for Groovy.
Groovy performance
Be aware that,
- Groovy isn’t always the best choice of language if your software has stringent performance requirements. Groovy objects extend from GroovyObject, which contains an invokeMethod(String name, Object args) method. Each time you call a Groovy method, that method isn’t called directly as it would in Java. Instead, it’s executed via the aforementioned invokeMethod(String name, Object args), which itself executes a number of reflection calls and lookups, which of course slows processing. The Groovy language developers have made several optimizations, and more will follow as future versions of Groovy take advantage of the new invokedynamic bytecode in the JVM.
- A quick performance tip here is to utilize the groovyserv library, which starts up the JVM and Groovy extensions, making your scripts run that much faster.
- Groovy has powerful XML and JSON parsing capabilities. Please refer Rick's "Groovy/Boon provide the fastest JSON parser for the JVM" post for detail. So Groovy can certainly be considered to do such XML/JSON parsing related piece of work in Java applications for performance and developer productivity benefits.
Also Refer
- Book: The Well-Grounded Java Developer - Part 3 - Polyglot programming on the JVM
- Groovy Fundamentals Course on Pluralsight
- http://www.slideshare.net/paulk_asert/groovy-power-features
Finally, I would say "Happy Groovy Learning" to java developers and let’s share your feedback in the comment.
After 2 weeks of writing this post, I thought to open discussion about the same topic in "Java Developers" group of Linkedin and got valuable viewpoints from intelligentsia of the group.
ReplyDeleteSo I highly recommend you to refer the comments from individuals here for additional information - http://www.linkedin.com/groups/Why-Java-developer-should-learn-70526.S.5894036066016440323
I heard the word that "Groovy" from this blog only.But this blog well explaining the segment about why java developers should learn Groovy and what are the major principle of it.Its really interesting.
ReplyDeleteWeb Design Company | Web Designing Companies
Your posts is really helpful for me.Thanks for your wonderful post. I am very happy to read your post.
ReplyDeleteBest Web Designing Company in Chennai
Your post are really nice & helpful. Thanks for sharing. But if anyone wants to be expert on Java than visit java basic concepts
ReplyDeleteMore suggested references,
ReplyDeleteGroovy presentations:
Groovy Tips
How to Get Groovy with Java 8
Github sample code snippet:
https://github.com/kousen/IntroGroovys
https://github.com/kousen/AdvancedGroovy