Monday, May 25, 2009

Running groovy scripts from command line

Groovy is another language for the Java Virtual Machine(JVM).
Further of the ubiquitous Java language programming, there are several alternative languages for JVM, such as Clojure, JRuby, Jython, Rhino and Scala, among others.
Groovy is a relative new language who incorporates features from widely adopted and accepted languages such as: Python, Smalltalk, Ruby, and of course Java, among others.

One catching feature is that Groovy allows rapid prototyping. As mentioned above, Groovy incorporates a lot of fancy features such as closures, implicit casting, powerful operators over data collections, etc.
In particular, I love the possibility to write a snippet of code and quickly check if it fulfills with my expectations.

Lets look a trivial example. You are a newbie Java programmer and you wish to know if you understand how a loop works. How do you that in Java:
  • Write a Java class
class Looping {
  public static void main(String args[]) {
    for (int i = 0; i < 10; i++) {
       System.out.println("i: " + i);
  • Save this file  as '', compile it 'javac' and run it 'java Looping'
Now, lets see how this can be done in Groovy (I assume that you usually work in a real operating system like Linux):
  • Write a text file
#!/usr/bin/env groovy
for (int i = 0; i < 10; i++) {
  println("i: ${i}")
  • Save this file as 'example.groovy', change its permissions 'chmod +x example.groovy', run it './example.groovy'. That's it.
No 'main' methods were required, no compilation of source code in JVM machine code; just write your code and run it.
Groovy offers a lot of interesting features. I mentioned just one that I considered useful for rapid prototyping, but there are more serious, well-elaborated, and amusing features that this modern language can offer.
However, the Groovy  Achille's heel is its poor performance. However, when current releases are compared with earlier releases we can say that great achievements has been made. (However, more work is required)

Anyway, if you are a Java developer and are starting to test new Java features and don't want lose a lot of time writing testing classes but scripts to test snippet of code, Groovy is an option. (...and slowly you'll start loving it and adopt it for production releases not just for testing purposes, I'll assure you :-D.)

Good hack!


1 comment:

John Sanabria said...

You can also write something like that:
// groovy code
good hack! :-D