Groovy

Groovy & Grails Understanding – Part 1

Introduction

Enterprises today require agile platform for rapid development of applications with ready assurance to quality of services, compliance to architecture and design standards. Two key things influence our ability to be agile. First, it’s the attitude of everyone involved. Second it’s the languages, framework, and tools we use to get our work done. There are languages and frameworks such as Groovy and Grails, emerge in recent years that support a more agile development approach. Groovy, is a dynamic language that works on top of the Java Virtual Machine. Groovy, developed in 2003 by James Strachan and Bob McWhirter [ 28 ], is a language that is very similar to languages like Ruby, Smalltalk, Python and Perl.

Grails is an open-source web application framework on top of the Groovy which exercise convention – over – configuration, honor the DRY (Don’t Repeat Yourself) principle, and is overall lightweight- making it a sound agile framework.

Groovy

Groovy is an object-oriented programming language for the Java platform. It is a dynamic language with features similar to those of Python, Ruby, Perl, and Smalltalk. It can be used as a scripting language for the Java Platform. It is dynamically compiled to Java Virtual Machine (JVM) byte code and interoperates with other Java code and libraries.

Groovy…

  • 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
  • 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 byte code so you can use it anywhere you can use Java

Architecture

Groovy uses a Java-like syntax which is dynamically compiled to Java byte code therefore Groovy can seamlessly work together with Java code and Java libraries. Groovy with Java make Groovy very powerful. When an application needs functionality that can’t be achieved with the existing Groovy libraries, the developer can still write Java code to achieve the goal and vice versa Java code can be converted to Groovy

Architecture
Figure 1: Groovy on Java Platform

Groovy is like a super version of Java. It can leverage Java’s enterprise capabilities but also has cool productivity features like action, builders and dynamic typing.

Groovy Development Environment

Groovy requires Java, so you need to have a version available (while groovy 1.6 supports JDK 1.4 or greater, for groovy 1.7 onwards, minimum JDK 1.5 is needed). Download the Groovy installer or binaries from the downloads page (http://groovy.codehaus.org/Download) and follow the installation instruction

Download binary

  • Set GROOVY_HOME
  • Add GROOVY_HOME/bin to your PATH
  • Set JAVA_HOME

Semicolons

The use of semicolons ( ; ) in Groovy is completely optional . The only time a semicolon has to be used, is when multiple function calls are placed on the same line

Semicolon

Data type declaration

When creating an object, it’s type doesn’t have to be defined explicitly. By using the def-keyword, Groovy will automatically detect what object type has to be used

Datatype

Although optional, Groovy still enables object types to be declared explicitly. This might be useful in situations where only one data type is allowed.

Groovy String

The Groovy String (Also called “GString”) allows for any type of logic to be integrated in the String definition. This can be done with the dollar symbol ( $ ) and (optional) braces ( { } ). The difference between a String and a GString is automatically recognized by Groovy.

Groovy String

Embedded quotes

Groovy has a nice way of working with Strings. In Java, a single quote would represent the primitive type char. In Groovy, anything that is surrounded by either single or double quotes is converted to a String. This is very useful when working with Strings that contain quotes. As this example will show, Strings with doubles quotes in it can be surrounded with single quotes en vice versa. To escape a quote, a backslash is used

Embedded

Collections

Groovy acknowledges three different types of collections. The first two, Lists and Maps, are no different from the ones used in Java. Lists use a null-based index to retrieve items, whereas Maps use a unique key to find an item. Ranges however, are more or less unique to dynamic languages. A simple example of a list in Groovy is:

Collection1

The first entry being zero in Roman, which is the word ‘nulla’ and doesn’t have a notation. A map is created by assigning values to a corresponding key, like such:

Collection2

Although ranges don’t appear in the standard Java libraries, most programmers have an intuitive idea of what a range is. Effectively, a range defines a start and an end point, with a notion of how to move from the start to the end point. Groovy provides literals to support for ranges, along with other language features such as the for statement, which understands ranges. Declaring a range is easy:

Collection3

Declaring Classes

Classes are the cornerstone of object-oriented programming, because they define the blueprint from which objects are drawn. The code below contains a simple Groovy class named Book, which has an instance variable title, a constructor that sets the title, and a getter method for the title. By default, all methods are public and therefore access modifiers are excluded.

Declaring Class

Return Statements

The last line of a method in Groovy is automatically the return statement. For this reason, an explicit return statement can be left out

Return

To return a value that is not on the last line, the return statement has to be declared explicitly.

Return2

Boolean

Every object in Groovy has a Boolean representation, which value depends on it’s content and type. A String for instance, will return true if populated and false if empty. This allows for quick “truth”-checking, and reduces the amount of code involved.

boolean

Operator overloading

Operator overloading allows the default use of operators to be overridden to enable a more intuitive approach for common methods. The way Groovy implements this, can be seen in the following table.

OperatorOverloding

Loops

Because of Groovy’s origin in Java, it natively supports both the for- and while-loop. Groovy’s for-each loops though, have a slight difference in syntax when compared with their Java equivalents. A Java for-each loop looks like this:

Loop1

Groovy’s counterpart however, uses the keyword ‘in’ instead of Java’s colon

Loop2

Groovy has some special capabilities for collections, among which the range. Groovy provides some extra looping techniques that can be used in collaboration with these. The each-method can be used on collections, and executes a given closure for each of the items in the list.

Loop3

The eachWithIndex does essentially the same, but keeps an numbered index that can be accessed from within the closure.

Loop4

Exception handling

Groovy lets the programmer decide to catch the exception or not. In the following example, the developer tries to open and read the contents of a file. He does not need to surround the method with a try and catch block, when he knows that the file exists. Groovy gives the programmer control over the exceptions, so he chooses to throw one but he does not need to. Java would not compile the code because it expects a try and catch block that throws the exception FileNotFoundException

Exception

The example above shows two ways of opening a fle: With and without a try and catch block. When the developers know that a file exists – As shown in the first example above – he doesn’t need to surround it with a try and catch. Like stated earlier, the developer can choose whether he wants to catch the exception or not – This happens in the second example above. Sometimes, code needs to catch more than one exception. Groovy allows the developer to catch all exceptions in one catch, instead of writing a catch statement for each try

Exception2

Note that the code above only throws one exception: The function openFile does not exist so it directly throws an exception. If it existed, another exception would be thrown since the URL is formatted wrong. The catch would show the exception: This is the same catch as the one from open File

Testing

Testing in Groovy is, like testing in Java, very extensive. A common way to test a application is with JUnit testing. The name for JUnit in Groovy is GUnit. Codehaus and IBM have written articles about unit testing in Groovy. Documentation on their findings can be found on the following websites:

Because the subject GUnit doesn’t support our main question, this will not be fully described. Basically, it is the same as JUnit testing.

Database Integration

Groovy provides the user with a wrapper around the standard Java classes, adding more functionality and ease of use when working with databases. It is important to understand that Groovy currently doesn’t replace all of Java’s original databases connectivity, as the JDBC is still in use.

Resources

 

Reference: Groovy & Grails Understanding – Part 1 from our JCG partner Nitin Kumar at the Tech My Talk blog.

Nitin Kumar

Nitin Kumar works as a Software Architect , predominately focus on Agile, TDD, Service Oriented Architecture, Grails and JEE. Besides working in software development, He writes technical articles and watches and studies new technologies
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button