Archive

Archive for the ‘Groovy’ Category

How Clojure improved my Groovy

January 15, 2010 7 comments

Dave Thomas and Andy Hunt have been saying for years that you should learn new programming languages. Doing so improves your skill in any language, whether you use the new language or not. I believed this with some skepticism, but decided nonetheless to start learning Clojure after reading The Pragmatic Programmer.

I’m reading and working through Programming Clojure, and one of the examples in the book looked like this:

(use '[clojure.contrib.str-utils :only (str-join)])
(str-join "-" ["hello", "clojure"])

Then, a week or so later, as I was working on some Groovy code, I saw something like the following:

def elements = ["It", "works", "on", "my", "machine!"]

def sb = new StringBuilder()
elements.eachWithIndex { element, index ->
  if (index == 0) {
    sb.append(element)
  } else {
    sb.append(" ")
    sb.append(element)
  }
}

assert sb.toString() == "It works on my machine!"

And I thought, “man, this code would be so much better in Clojure!” Since I can’t use Clojure for my job (yet), I set out to find a better way to do this in Groovy. I decided to look for something similar to Clojure’s str-join for Groovy, and I found the join() method. It does exactly what I needed!

def elements = ["It", "works", "on", "my", "machine!"]

def sb = new StringBuilder()
sb.append(elements.join(" "))

assert sb.toString() == "It works on my machine!"

And so, I discovered for myself that Dave and Andy were right. Knowing Clojure (specifically, the clojure-contrib library) helped me to write better Groovy code.

Advertisements

SnakeYAML and Groovy

January 13, 2010 5 comments

I had some fun playing with SnakeYAML and Groovy the other day. Below are some of my results. If you want to run this in your groovyConsole, you need to download SnakeYAML and add the snakeyaml-<version>.jar to your classpath.

From YAML to Groovy:

import org.yaml.snakeyaml.Yaml

Yaml yaml = new Yaml()
def obj = yaml.load("""
a: 1
b: 2
c:
  - aaa
  - bbb""")

assert obj.a == 1
assert obj.b == 2
assert obj.c == ["aaa", "bbb"]

From Groovy to YAML:

import org.yaml.snakeyaml.Yaml

def map = [name: "Pushkin", aliases: ['P', 'Push']]
Yaml yaml = new Yaml()
String output = yaml.dump(map)

assert output ==
'''name: Pushkin
aliases: [P, Push]
'''

Isn’t YAML so much simpler and cleaner than XML? Why aren’t more of us using YAML with Java and Groovy?

Mocking and stubbing in Groovy with ‘with’

October 5, 2009 1 comment

I often use metaClass in Groovy to create mocks or stubs in my unit tests. Recently I’ve discovered that the with method makes this a bit simpler.

This:

Foo.metaClass.with {
  doSomething = {
    return true
  }
  anotherThing = {foo ->
    assertEquals 42, foo
  }
}

is slightly shorter than this:

Foo.metaClass.doSomething = {
  return true
}
Foo.metaClass.anotherThing = {foo ->
  assertEquals 42, foo
}

and less code means less bugs.

[Update: For more explanation of why the with method is so great, read this post.]
[Update: And for another way to write your mocks and stubs, see my previous post on mocking with Groovy.]

Who needs a mock framework?

July 26, 2009 12 comments

In Groovy, you can create mocks & stubs using native language features, so you can forget about learning a mock framework.

class Author {
  def getName() {
    return 'Josh Brown'
  }
  def isFamous() {
    return false
  }
}

Let’s stub the isFamous method:

def author = [isFamous: {true}] as Author
assert 'Josh Brown' == author.getName()
assert author.isFamous()

(If you haven’t already, stick the above code in your groovyConsole, run it, and play around with it.)

When mocking and stubbing are so easy to do with the language itself, using a mock framework is overkill.

[Update: Bob Martin recently wrote an excellent post about Manual Mocking.]

Tags: , ,

Story time with easyb

January 27, 2009 2 comments

Everyone loves a good story.
 

Star Wars Trilogy

 

With easyb, you can write stories in your code!

scenario "the Death Star destroys Alderaan", {
    given "the Death Star", {}
    and "Alderaan", {}
    and "Alderaan is targeted by the Death Star", {}
    when "the Death Star fires", {}
    then "Alderaan is destroyed", {}
 }

You probably could’ve written that with the stakeholders yelling over shoulder. No – the Death Star should destroy Yavin IV, not Alderaan!!! If you’re writing readable code in front of them, you might be able to get them to make a decision while you’re at your keyboard.

Now you have executable documentation, and the stakeholders can leave the party. And once they’re gone, you can move on to writing some Groovy code to fill in those empty squiggly braces:

scenario "the Death Star destroys Alderaan", {
    given "the Death Star", {
        deathStar = new DeathStar()
    }
    and "Alderaan", {
        alderaan = new Planet(name:"Alderaan")
        Galaxy.planets << alderaan
    }
    and "Alderaan is targeted by the Death Star", {
        deathStar.target = alderaan
    }
    when "the Death Star fires", {
        deathStar.fire()
    }
    then "Alderaan is destroyed", {
        Galaxy.planets.shouldNotHave alderaan
    }
}

Now run it and watch it fail. Ah, the joy of xDD…

From here, you can write the DeathStar, Planet, and Galaxy classes you need to make it pass. Run it again! Refactor! Repeat!

Now you have documentation that’s readable, executable, and verifies that your code does what it’s supposed to do! Wasn’t that easy?

Tags: , , ,

[].inject(“Groovy”){}

January 25, 2009 7 comments

The collection helper methods like each, findAll, and collect are among the clearest productivity advantages of Groovy over Java. For reference, here’s a list of the common collection helper methods on the Groovy Quick Start page (after opening the link you’ll have to scroll down to them).

The inject method is among the most interesting of them all but is not utilized often by Groovy developers. It’s useful but somewhat difficult to understand, relative to the complexity of the other collection helper methods, so many developers get the job done without inject and never bother to learn about it. I encourage everyone to learn inject so that they can understand another approach for attacking their problems and choose the most appropriate approach. The inject method is also a great first step in learning a little about functional programming.

Functional Style – A stork story for inject
The Scala and Clojure languages on the JVM have aroused interest in functional style programming. Even with an imperative language like Java we can alter our programming style to more of a functional one, so learning the functional tenets can be very valuable to your arsenal.

Let’s take some Groovy code that calculates the sum of numbers 1 through 10.
def total = 0
(1..10).each{total += it}
return total

Here we apply a closure to each value in the 1..10 range. But as we repeatly apply this closure we also need to keep track of a total variable, which changes with each iteration.

In pure functional programming variables are… not allowed. This poses an interesting twist to our problem. How can we accomplish the same functionality as the above code without any variables?

The answer to most “How can I solve this without variables?” questions: Recursion.

Let’s examine how we totaled up values 1 to 10:
(((((((((((0)+1)+2)+3)+4)+5)+6)+7)+8)+9)+10)
Each set of paranthesis describes the value of total at some given point in time starting with 0 and expanding out to its final result of 55. Consequently, total gets set to 11 different values over its lifetime and only the last of those 11 was actually what we wanted.

The other danger here is that another developer might “refactor” your code by moving all variable declarations to the top of methods. I’ve inherited Java code like this quite often, where the beginning of some ginormous method sets a bunch of values like total = 0, even though taking the initializing value out of context actually makes the code more confusing.

With inject we can make the value of total clearer by keeping the calculation within the scope of its declaration. We “inject” the initial value of 0 and at each iteration the previousResult value represents what used to be represented by a waffling total variable.
def total = (1..10).inject(0){previousResult, iterationValue ->
  previousResult + iterationValue
}

The concept of inject in Groovy is identical to that of a left fold in functional programming. Ironically, the Groovy’s implementation of inject does not use recursion for, what I’m assuming, are performance reasons.

sum()
We’ve been using a very simple example. Those familiar with Groovy might ask why not just use the sum() method available to lists:
(1..10).sum()

Well, I’m glad you brought it up because there’s more to sum() than you may have realized.

You see, sum() allows you to “inject” an initial value.
(1..10).sum() // 55
(1..10).sum(0) // 55
(1..10).sum(3) // 58

This doesn’t seem incredibly valuable at the surface, but let’s look at why it can be.

Try calling sum() on an empty list:
[].sum() // null

Yes, the result is null. Most folks would assume that the result should be 0. So why isn’t the result 0? You have to realize that the sum() method merely requires that the objects in the list have a plus() method, which means that Groovy’s sum() method can’t assume that the empty list you passed in held Integer values.

For example, you could join strings in a list using sum():
["strings ","in ","a ", "list "].sum() // "strings in a list"

If you had an empty list intended for Strings, a sum() of 0 doesn’t make sense – an empty String would be more appropriate, so use sum(""). If you don’t “initialize” a value into sum() you could end up with null if your list is empty and that could break some assumptions in your code, leading to a NPE. It’s often a good idea to “initialize” the sum() method with a value, much like you would do with inject().

inject() to build collections
Java programmers switching to Groovy often use each{} for everything involving iterations. They write the equivalent of an imperative Java for loop:
def oneToTen = (1..10)
def doubles = []
oneToTen.each{myValue->
  doubles.add(myValue*2);
}
return doubles

They’re often thrilled to find out that using a different collection helper method makes their code more readable and concise:
def doubles = (1..10).collect{ it*2 }

Always scan your Groovy code for a collection helper method code smell:
If your each{} or other collection helper method (findAll, collect, etc.) has a variable declaration in the line before it, you’re likely to benefit by using a different method.

I usually play around in the GroovyConsole (just type groovyConsole in your command line if you have Groovy installed) to decide which collection helper method does the job best. It’s a fun challenge to include inject into the mix even though it has only emerged once as the victor in my production code… and honestly I can’t remember what that was and I don’t have access to the code any more. Bummers.

There’s an inject example at the bottom of a post we made on chaining and currying closures back in November ’08. Chris made a clever improvement in the comments section of that post as well. Thanks for that, Chris! We greatly welcome any improvements or questions here and we hope to see even more in the future from our readers.

How to use Groovy without management finding out

November 20, 2008 5 comments

I hang out with Ruby guys and gals when I can. These folks are such a blessing to my brain. If you don’t have Ruby friends, find some. Google for “yourcity ruby brigade” to find a Ruby user group in your area.

I’ve often heard Ruby friends talk about utilities they wrote in Ruby that essentially generate boilerplate Java code, and I used to shudder at the thought.

I always figured “You have a great language that can do so many yummy things, why are you using it to write icky code!?”

I think I’m beginning to understand now: The icky language (sorry for the blasphemy, but yes, I mean Java) runs faster. It’s also more likely to be accepted by the governors in your projects. If you don’t know what I mean by governors, they’re the poor folks that take the heat and lose bonuses when stupid geeky experiments with unproven technologies ruin a project. These folks love the status quo. And bonuses. Your geeky technologies pose a threat to both.

Groovy noobs and doubters ask “How can I get management to approve using Groovy in my project?” Well, you can write Groovy scripts that no one needs to know about. Write scripts that generate Java code.

I’m not completely off my rocker.

Grails does some cool code generation to write Groovy views and controllers based on your tiny li’l POGO domain classes. It’s so awesome not to have to write boilerplate code or have to start everything from scratch. I can literally create an entire CRUD webapp in a couple minutes, even with a couple beers in me (which, for the record, only happens at home on my own time – I swear). Why code generation is awesome: Doing tedious code manually from scratch is like a coding limbo… never really touching heaven or hell but it passes the time.

Code generation good. Hulk like code generation. Tedious code make Hulk angry! Hulk smash!!!!!

Just to play around and set my first goal low, I challenged myself to write a Groovy script that creates a Java constructor. All my favorite IDEs do this for me already, but I’m not going to let practicality get in the way of fun… certainly not when I’m coding on my own time at home! Time to play!!!

class Person{
  private String firstName;
  private String lastName;
  private int age;
}

void constructor(Class clazz){
  def props = clazz.properties.declaredFields.findAll{
    // filter out the properties I do not want
    !it.toString().contains("static") &&
    !it.toString().contains("metaClass")
  }.collect{
    // I want the property type and name
    [it.type.toString().split()[-1].replaceAll('java.lang.',''), it.name]
  }
  // dump out the constructor!!! yay!!!
  print " public ${clazz.name}("
  print props.collect{"${it[0]} ${it[1]}"}.join(', ')
  println "){"
  props.each{ println " this.${it[1]} = ${it[1]};"}
  println " }"
}

 

constructor(Person)

All I have to do is paste in a new class definition like I did with the Person class and call my dandy new constructor() method, passing to it the name of my class. In Groovy I don’t have to say Person.getClass() or even Person.class – just plain ol’ Person is good enough.

My console dumps out:
  public Person(String firstName, String lastName, int age){
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
  }

Not too shabby.

Keep in mind the DRY principle. Your first priority is to write Java code without any duplication. In most cases you can avoid duplication by simply following basic OO principles.

If, however, boilerplate code seems like a necessity, consider generating it.