Thursday, December 26, 2013

Groovy Language Features

Will look at some of language features in Groovy that makes this language so dynamically groovy and easy to learn and use.

1. Less code more results.

Line terminating semicolon not required, unless more than one statements are being written on the same line.

Groovy imports the following packages by default:- java.lang.*, java.util.*, java.io.* and java.net.* so no explicit import statements are required. The following classes java.math.BigDecimal, java.math.BigInteger are also imported by default in addition to the groovy package groovy.lang.* and groovy.util.*

Classes and methods are public by default.

Groovy understand print and println, so no need to to have System.out.println. Return statement is always optional.

Java Version:










Groovy Version:










2. Groovy Data Types

Objects Objects Objects, everything is Groovy are objects even functions which are first class citizens and can be passed around as blocks or closures. Unlike Java which distinguishes between primitive types (boolean, byte, char, double, float, int, short) and references (Object and String), Groovy does not have any notion of primitive types in fact it uses the wrapper classes already available in the Java language :-
 java.lang.Byte
 java.lang.Short
 java.lang.Integer
 java.lang.Long
 java.lang.Float
 java.lang.Double
 java.lang.Character
 java.lang.Boolean
Groovy datatypes can be explicitly defined using types as in java








Groovy can implicitly determine the types dynamically when using the def key word.







3. Better Loops

Groovy supports the traditional for loop loop as in java :





In addition Groovy offers groovier ways of looping...
Range Loop
Range loop take the form 0..2 i.e start from 0 until 2.





Upto Loop
Upto loop takes an integer as an argument and expect a closure for the steps to execute.






Times Loop
Unlike the upto loop which takes an lower and upper bound, the times loop will execute for a fixed number of times.





Step Loop
As the name suggests the Step Loop allows step through an execution sequence by specifying lower and upper bounds and subsequent steps.

$it is a special variable which represents the current index in the loop being executed.

















4. Safe Navigation Operator (?.) and Elvis Operator (?:)

The safe navigator operator allows to eliminate redundant null checks. In most cases when one references an object we may need to verify if the object is null before invoking any actions on it. The safe navigation operator is a convenient way of letting groovy perform this check.





In the above code, the safe navigation operator will make sure that the dep object is valid and not null before returning the department code.

The Elvis operator is similar to the Java ternary operator and is used to evaluate statements with default values.






5. Equals and ==

In Groovy the is() method is equivalent to Java's identity method i.e. the java equals() method, where we check that the two objects are the same. 

The == is a smart equality check that can be used to check equality of values, Groovy will automatically take care of any null checks.










6. Groovy Beans

Groovy beans truly bring out the meaning of JavaBeans by defining what they truly are objects with properties.














There is less clutter when defining Groovy Beans. Properties are defined using def keyword or using explicit type definition as String, Integer etc.. Groovy will create getters and setter methods behind the scene.






When we call the member variables, we are executing the corresponding getter methods and not directly referring to the member variables.  If properties need to be made read only, the properties need to be declared with the final keyword in which case Groovy will only provide getter methods.










Name arguments can be used to construct Groovy Beans as well,











Until next time, Thank you
Malcolm

Saturday, December 14, 2013

Introduction to Dynamic Languages for the JVM - Groovy

What are JVM Dynamic Languages?

Before diving into the discussion of what are dynamic languages let us touch briefly touch upon statically typed and dynamically typed languages. 

Static Typing - A programming language is said to use static typing when type checking is performed during compile-time as opposed to run-time. Static typing is a limited form of program verification where type safety checks are made i.e. validate that the correct data types are used and correct values are applied for the given data types. Program execution may be made more efficient by omitting runtime type checks. Java, C, C++ are examples of statically typed languages.

Dynamic Typing - A programming language is said to be dynamically typed when the majority of its type checking is performed at run-time as opposed to at compile-time. In dynamic typing values have types, but variables do not; that is, a variable can refer to a value of any type. Dynamic typing may incur some performance implications since type safety checks are applied at runtime moreover the checks are repeated for every execution of the program, however Dynamically typed language systems run-time checks can potentially be more sophisticated than those of statically typed languages as they can use dynamic information as well as any information from the source code to add dynamic runtime features to the program or extend the existing behavior of the API.  JavaScript, Ruby, Python, Perl, Groovy are examples of dynamically typed languages.

Java Virtual Machine - The Java Virtual Machine executes java programs which have been translated into bytecode by the Java compiler, the execution of machine independent bytecode and the security features provided by the JVM makes the JVM a very suitable platform supporting slew of dynamic languages that  run on the JVM. 

JSR 223 - Scripting for the Java Platform was the first attempt to bring dynamic language support to the JVM,  the JSR specified a framework for hosting scripting engines in Java that compiles or interprets scripting code and then executes it. This specification and its implementation made it much easier to create applications that include both Java code and scripting code.  JSR 223 was included in Java SE 6 and implemented in JDK 6 which included the Rhino Scripting engine an implementation of the JavaScript scripting language. However providing these scripting engines was no easy tasks, developers for these dynamically typed engines needed to adhere to the requirements of the java bytecode that the JVM executes which was designed exclusively for statically typed language.  

JSR 292 - Supporting Dynamically Typed Languages on the Java Platform is the next step in providing support to dynamic languages on the JVM, basically solving the inherent problem in trying to fix a square peg     :- dynamic language support into a round hole -: adhering to the JVM requirements which support statically typed language. This is achieved by introducing a new java bytecode instruction for the JVM - invokedynamic which is a new method linkage mechanism. JDK 7 includes a new package, java.dyn, that contains the classes associated with dynamic language support in the Java platform.  

What is Groovy ?  

From the Groovy site, Groovy is
  • An agile, dynamic language for the Java Virtual Machine.
  • Builds on the strength of Java
  • Makes modern programming features available to Java developers with almost-zero learning curve
Lets try to examine these some more.

Agile

Groovy is small, concise and simple. As a developer you want to spend more time focussed on delivering customer value and avoid having to write boiler plate code, Groovy provides this agility, by making programs smaller, easy to understand and easier to test, general rule of thumb less code means less tests and less bugs.

Builds on the Strength of Java

Groovy is a dynamic language that runs on the JVM, Groovy seamlessly integrates with Java and many parts of Groovy are written in java. Groovy syntax is much similar to Java and in a true sense complements Java.  Groovy code and Java code can be mixed to existing Java libraries and apis can be easily used in Groovy.

Modern Programming features

Groovy offers additional features over the Java language features by adding additions to the Java standard classes via the GDK (Groovy Development Kit). Groovy offers features like Closures, I/O Additions so that file handling is much simpler, rich additions for collections packages. GPath allows for simpler handling of XML data much similar like XPath. Everything is groovy is an Object, even functions are first class citizens and can be passed around just like objects. 

How can Groovy be used ?

Groovy for Scripting

Groovy can be used to create scripts for every day tasks, much similar that to a PERL or UNIX scripts. Leveraging on ones existing Java experience, Groovy scripts fill the gap where pure Java Developers could not script something very quickly. Lot of commercial tools offer support for Groovy scripting example: SOAPUI

Groovy Applications

The real strength in Groovy is full fledged applications especially the web application framework - Grails for quick MVC applications and Thin Server Applications (HTLM5) with various grails plugins. 

Getting Groovy

Groovy can be downloaded from http://groovy.codehaus.org/Download, 2.2 being the latest version as I pen down these thoughts. Installation instructions can be found at http://groovy.codehaus.org/Installing+Groovy.

Groovy Components 

groovysh

Groovy Shell provides an interactive shell to type and execute groovy command on the fly.  Invoke the Groovy Shell by typing groovysh on the command line.











groovyconsole

GroovyConsole provides a swing interface and acts as a minimalistic Groovy interactive interpreter. It allows to load external groovy scripts via the file menu and allows editing and saving groovy scripts.


groovy

The groovy command / interpreter is used to execute groovy commands and scripts.










groovyc

Groovyc is the groovy compiler which compiles java byte code from the groovy source files. The groovy compiler generates class files for each groovy source file.






Simple Groovy Project

Lets looking at some ways of getting started with creating Groovy projects.

Basic Project 
Most IDE's (Eclipse, SpringToolSuite, IntelliJ, NetBeans) offer good Groovy support via plugins which are quite mature. The standard way for creating groovy project is described here.

Maven Project
In case of Groovy Maven project, the simplest way to kickstart is to start with a regular java project and then update the pom with required Groovy dependencies i.e. Groovy-Eclipse compiler plugin dependencies and the groovy-all jar dependency. 

Lets try to walk through these steps.

1. Create Java project using the maven archetype
mvn archetype:generate -DgroupId=com.malcolm.groovy.projects -DartifactId=com.malcolm.groovy.simple -DarchetypeArtifactId=maven-archetype-quickstart










2. Import maven project into eclipse.











Add required Groovy source folders and update the pom to support groovy dependancies,








Update the pom, to include he following,
groovy-eclipse-compiler - Plugin for Groovy Compiler
build-helper-maven-plugin - Plugin to help find Groovy Source Codes
groovy-all - Groovy jar dependency



The simple groovy java project is a simple kickstart project that uses Java and Groovy seamlessly.

1. Simple Java Interface for getting Square Root of a number.

2. The Java implementation returns the Math.sqrt() value, while the Groovy implementation would use Newtons method to get Square root by approximations.


3. Parameterized Junit test case for testing the Groovy implementation from Java.


4. Parameterized Groovy test case for testing the Groovy implementation from Groovy.


Graddle Project

Graddle by far is the simplest way to get started with Groovy project, all that is need is to apply the garddle groovy and java plugin and all is done.



Source code from simple groovy project available on GitHub - https://github.com/MalcolmPereira/com.malcolm.groovy.simple




Until next time, Thank you
Malcolm

Back to Groovy Thoughts