Home > Groovy > How to use Groovy without management finding out

How to use Groovy without management finding out

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.

Advertisements
  1. marverde
    November 25, 2008 at 10:55 am

    you have a really great blog here!! massive big up! i will follow it from now on!

  2. nikola
    November 27, 2008 at 5:21 am

    i’m getting next error …. Exception thrown: org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed, Script1: 17: expecting ‘}’, found ‘public’ @ line 17, column 11.
    1 error

    could you help me….

  3. November 30, 2008 at 6:38 pm

    @nikola – Thanks for pointing this out. WordPress is turning our single and double quote characters into smart quote characters. We’ll look into disabling this character-swapping feature.

    In the meantime, you can make the code work by simply changing those characters back to the normal kind.

  4. nikola
    December 3, 2008 at 5:41 am

    it worked, thanks…

  5. January 14, 2009 at 10:00 am

    easyb might be another way to introduce Groovy without management finding out. And it might also help with bad requirements.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: