Friday, September 7, 2012

Say hello to Groovy – Part 2 (Operators & Control Structures)

In my last blog, I gave an introduction to Groovy. We looked at the typical hello world program in Java as well as Groovy to understand how some of the additional features provided by Groovy helps to cut down on a lot of boilerplate code that you would have otherwise written in Java. In this blog, I will concentrate on some of the operators and control structures which are unique to Groovy.

Groovy Truth

Like Java, Groovy supports standard conditional operators in a Boolean expression. In addition to this, any type can be evaluated as a Boolean expression in Groovy. This is possible because Groovy has rules to convert a non-boolean objects to a Boolean value. E.g. In case of string, non-empty strings evaluate to true


Following are some of the rules that you should know: 
1. Empty collection evaluates to false. 
2. Non-zero numbers evaluates to true. 
3. A non-null object reference evaluates to true. 
4. Non-empty Map evaluates to true. 
5. Iterators/enumerators evaluates to false if it has no further elements. 

Operator Overloading

In Java we use the == operator to see if the variables are referring to the same object instance. Groovy overrides == operator on types such as String, Integer, List etc., to check for content equality rather than object equality. To test if two variables are referring to the same object instance in Groovy we use the is () method.





Elvis Operator (?:)


The "Elvis operator" is similar to Java's ternary operator. It can be used for returning a 'sensible default' value if an expression resolves to false or null. E.g. In below snippet, if username is null or empty, “Anonymous” would get printed. 


Safe Navigation Operator (?.)


In Java, it’s a common practice to check for null, before invoking a method on the object to avoid NullPointerException. In Groovy, this is achieved in lesser lines of code using the Safe Navigation operator. The safe navigation operator will simply return null instead of throwing an exception, e.g: In the below code snippet, null would get printed and no NPE will be thrown.



Looping

In addition to all looping constructs available in Java, Groovy provides some extra ways to loop and execute a piece of code. Groovy extends the Integer class with the step (), upto () and times () methods. If we have a List in Groovy we can loop through the items on the list with the each () and eachWithIndex () methods. We will revisit this with examples when I cover closure and collections.


Exception Handling

Groovy doesn’t force you to handle exceptions within the method signature not even for checking exceptions. You are free to choose how and when you handle the exception. The exception is passed on to the calling code until it is handled. E.g. the following is a valid code in Groovy however if you were to write the same code in Java, the compiler would have forced you to handle java.net.MalformedURLException.


Sunday, September 2, 2012

Say hello to Groovy - Part 1

With this blog, I am starting a series on Groovy. Chances are that you are already aware of what Groovy is but in case you are not; Groovy is an object oriented programming language.

Groovy is one of many JVM languages that compiles to bytecode that runs on the JVM. Groovy is also a dynamic language so it’s not statically typed like Java however it has a Java like syntax.It's also a scripting language so you don't necessarily have to compile the groovy code before executing it.


So why would you choose Groovy over Java or other dynamic languages that runs on the JVM like JRuby? While Java like syntax is definitely a plus, Groovy is designed to seamlessly integrate with Java i.e. you can implement a Java interface using Groovy and vice versa.
One other advantage is that Groovy has many modern programming features which were missing in Java e.g. Closure. If you are a Java developer, learning Groovy would be a cakewalk!

 
Getting Started
In order to get started, perform following steps:
  1. Download the latest version of Groovy from http://groovy.codehaus.org/Download.
  2. Once downloaded, extract the content of the zip file into your location of choice e.g. C:\groovy-2.0.1
  3. Create an environment variable called GROOVY_HOME and set it to C:\groovy-2.0.1
  4. Append  %GROOVY_HOME%/bin to the path environment variable.
Once you are done open a command prompt and type groovy - version. If Groovy's version is displayed in the command prompt you are all set to play with it!

 
Walkthrough of Groovy tools

Now that you have Groovy installed, lets look at the tools that you would need to play with it.

groovy - Use this tool to execute groovy source code (.groovy files).  This is typically used for executing Groovy scripts.

groovyc - Use this tool to compile groovy code to Java class file. You would use this tool so that you Groovy source code is not compiled every time before execution.

groovyConsole - This is a minimal editor that you can use to load, type and exceute Groovy code.



 
Typical Hello World

Introduction to any programming language is incomplete without a Hello World program so lets see how a hello world program looks like in Groovy.While we are at it, we will also see how Groovy cuts down on a lot of boilerplate code from Java. Here is how a typical Hello World program would look like in Java.


Here is the list of Groovy features that we are going to leverage :
  1. Default visibility for methods and fields in Groovy is public.
  2. It is a dynamic language so type information is optional.
  3. Semicolon is optional at the end of a statement.
  4. Paranthesis is optional for top level expression.
  5. Groovy provides println which can be used in place of System.out.println. You can use println "Hello World!" inplace of System.out.println("Hello World!");
Once we factor in all the above mentioned features, this is how a Hello World program would look like in Groovy.

Ok. I also mentioned that Groovy is a scripting language so it automatically wraps a script with a default class and main method. So your hello world program in Groovy can actually be a single line of code.



Enhanced Hello World

Now that you got an idea of how Groovy cuts down the boilerplate code and enhances developer productivity, lets look at an enhanced Hello World program.

Here is the enhanced version of Hello World code in Java



lets leverage some of the Groovy features mentioned below and rewrite the same program in Groovy:
  1. Groovy has a feature called Gstring which allows you to write a string containing an expression that can be evaluated. e.g. instead of "Hello "+getName()+"!" you can use something like "Hello $name!"
  2. It also has something called Groovy Bean i.e. if you have a public field or property in a bean class, Groovy automatically generates getter and setter for it. Groovy also provides shortcut to access and set these properties. e.g. in the above example, instead of hello.setName("world") you can use hello.name = "World"
Ok. So this how it will look in Groovy.

 


that's it in this blog. In my next blog i will do a deep dive on some of the Groovy feature.