DevOps Zone is brought to you in partnership with:

Ganesh Samarthyam is an independent trainer, consultant, and author. He has 11+ years of experience working in the industry. Earlier, he worked in Siemens Corporate Research and Technologies Bangalore and Hewlett-Packards' C++ compiler team. His areas of interests include OO design, design patterns, and programming languages. He is a Software Engineering Certified Instructor (IEEE certification) and has an OCPJP 7 certification. His recent book is "Oracle Certified Professional Java SE 7 Programmer Exams 1Z0-804 and 1Z0-805: A Comprehensive OCPJP 7 Certification Guide" published by Apress in 2013 (see http://amzn.com/1430247649). Sg has posted 1 posts at DZone. You can read more from them at their website. View Full User Profile

Productive Programming in Groovy

12.04.2013
| 16010 views |
  • submit to reddit

The only thing constant in this world is change! In the 1990s, Java shook up the computing world by bringing managed runtime (virtual machines) to mainstream programming. Today, there are many new languages emerging to replace languages that are popular today. For JavaScript, some attempting to replace them are TypeScript (Microsoft) and Dart (Google). For C/C++, attempts to replace them include D language and Go (Google). Interestingly, for Java, the main competition comes from languages that are built on top of the Java environment itself! 

Did you know that there are more than 200 languages that target the Java platform? Languages like Scala, Clojure, Groovy, JRuby, and Jython are few but important languages that target the Java platform. Of these, of interest to us is Groovy since it is getting wide attention and gaining steady popularity in the last few years.

Why Choose Groovy? 

I  started working in Groovy entirely by chance. I was trying to write code for my pet project and realized that Java was slowing me down. I explored using alternative languages, but couldn’t. Why? There are many reasons, which will be of interest to you as well when you try to start using Groovy, so I’ll discuss them in detail here. My comparison is mainly with Python and Ruby since they were the popular alternative languages I considered. 

First, I had considerable experience programming in Java and in using the Java libraries and framework. When I move to languages like Python or Ruby, I have to leave my familiar land and learn the language and the eco-system. Java’s main advantage is the vast set of libraries and frameworks (most of them free and open source) and I am likely to lose them with such a move. I considered using Jython and JRuby - but I preferred Groovy because I could seamlessly switch back and forth between Java and Groovy (since Groovy is more or less a superset Java). 

Second, I had little spare time to spend learning a new language from scratch. Groovy has Java-like syntax and hence the learning curve is not steep. Once I installed Groovy, I could straightaway start programming in Groovy since I code mostly in Java and gradually move on to more “Groovyish” code. 

Third, I had to consider deployment aspects as well. Though Python and Ruby are also installed in a millions of machines, Java runtime is ubiquitous. That meant I could just ship Groovy jar file along with my application and get the program working in any machine. 

In short, moving from Java to Groovy was like shifting my home from India to Australia - it is a familiar terrain but still I need to know many things to survive there. For me, moving from Java to Ruby or Python is like moving from India to Antartica - it is a completely different terrain - yes, I am game for adventure, but not now when I have immediate work to get done!  

I will confess the fourth reason that is non-technical: I liked Venkat Subramaniam’s excellent book on Groovy [2] and his presentations on Groovy. Being a like-minded geek, I decided to try, learn, and start using Groovy.

What is Groovy? 

Groovy is a dynamic language that dynamically compiles the code to the Java platform. It is popular as a scripting language and also widely used for unit testing Java code. Groovy is open source (Apache v2 license) and is backed by VMware. James Strachan conceived the idea of Groovy language and started development in 2003. The current (as on November 2013) stable release is 2.1. You can use Groovy in most common operating systems - Linux, Windows, and Mac. 

Groovy is also reasonably popular. It made headlines when Groovy entered the top 20 list in the widely cited TIOBE language popularity index in October 2013 (it was in 53rd position in 2012!). There were 1.7 million Groovy downloads in 2012. We need to take these figures (especially on popularity) with a pinch of salt; nevertheless, it is safe to say that Groovy is gaining steady popularity in the last few years.  

Can you Show How Groovy is “Better Java”?

Hello World Example

Let’s start with the classic “hello world” example: 

class Hello {
	public static void main(String []args) {
		System.out.println("hello world");
	}
}

The code that is marked strikethrough is to show that those parts of the Java code is not need in Groovy - this simple and sweet println will do:   

println("hello world")

First (Simple) Example 

How about writing code for implementing the “type” command (or the “cat” command) but that is limited to printing the file names passed as argument? Here is the Java version:

import java.io.*;

class Type {
	public static void main(String []files) {
		// process each file passed as argument 
		for(String file : files) {
			// try opening the file with FileReader 
			try (FileReader inputFile = new FileReader(file)) { 
				int ch = 0; 
				while( (ch = inputFile.read()) != -1) {
					// ch is of type int - convert it back to char
					System.out.print( (char)ch ); 
				}
			} catch (FileNotFoundException fnfe) {
				System.err.printf("Cannot open the given file %s ", file);
			}
			catch(IOException ioe) {
				System.err.printf("Error when processing file %s; skipping it", file);
			} 
			// try-with-resources will automatically release FileReader object  
		}
	}
}

Now, what I don’t like about this code is it is too verbose. Also, why should I worry about low-level details like reading characters as integer, converting the integer back to character, checking with -1 to check end-of-file, etc? 

As many of you know, Java 7 introduced NIO.2 which simplified much of the file and I/O processing. With Java 7, the code looks simpler when compared to the earlier versions of Java, but still looks verbose: 

import java.nio.file.*;
import java.io.IOException;

class Type {
	public static void main(String []files) {	
		// process each file passed as argument 
		for(String file : files) {
			try {
				Files.copy(Paths.get(file), System.out);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

Compare this with Groovy version which is a sweet one-liner: 

args.each { println new File(it).getText() }

Traversing a data structure is easy in Groovy - you can use “closures” instead of plain loops and use each() method as done in this case. Groovy helps you work at higher levels of abstraction (like most other scripting languages). Since file processing is a common task in scripting languages, Groovy provides a higher-level abstraction to this functionality, and hence the code is much simpler. 

Published at DZone with permission of its author, Sg Ganesh.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Raghavan Alias ... replied on Sat, 2013/12/07 - 1:17pm

That is a fantastic article Ganesh. I have been reading your articles in OSFY magazine. Good to see your book on OCAJP series as well. Hearty Congratulations and best wishes!!

Sg Ganesh replied on Sun, 2013/12/08 - 2:46am in response to: Raghavan Alias Saravanan Muthu

Thank you for your kind words - glad to know that you liked the article :)

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.