Groovy

Why I’m not using Groovy at work

Posted on December 14, 2009. Filed under: Grails, Groovy, Uncategorized | Tags: , , |

A disclaimer: this blog is based on my personal failures with getting Grails accepted in our company. So, no, this is not the holy grail into dropping your EJB, Struts or Java toolkit to get groovy with Grails, but maybe you can learn something on how NOT to do it, and post some comments on your experience.

Introduction
2.5 Years ago, I got my first cup of Grails. It was some time before the Groovy/Grails Exchange 2007, which I visited consecutively. As a result of that visit, I had Graeme Rocher over to our company to give a presentation about Grails (almost 0.4 at that time), and I expected the rest to follow naturally (the rest being: drop all our Java development and take up Grails for all of our web development). I was a little naive in that, I experienced the couple of months after that. Not even did we not drop all our Java development: we dropped none, nor did we picked up any of the cool features Groovy or Grails offered. Instead, people went crazy with frameworks like Wicket, SEAM and other cool stuff, like..ehh…EJB’s…

However, in my spare time I never left Grails and I used it for a lot of prototype applications, especially because the ease of setting up a complete project with Spring/Hibernate integration, etc. And also because it’s just fun to use the power the Grails framework harnesses. Anyway, I never could convince people to seriously use it. I inspired some people to use it, but only for short periods. The lack of IDE support didn’t help in that, and with the thousands of frameworks around, you’ve got to make a choice somewhere. However, I haven’t given up on Grails, and I still try to use it as much as possible. So, when I started for myself in April as an independent (though I do favor certain technologies!) consultant, I thought: this is my chance! I can now focus on Grails technologies. However, even though I’m not quite inexperienced with Grails, I found it hard to find a good (well, any actually) project which was open to Grails, so I found a different project, in which I could focus on other things (like ATDD/TDD, XP, and other quality related things).

However, then, all of a sudden my manager showed some interest in Grails (might not be the best reason to use Grails btw, but it’s great that this is without any resistance!), and we decided to take on a project in Grails. There, the problems started. (Note: I don’t blame anyone in this, except myself: I should have used a different approach. That’s part of reason for writing this blog, to prevent you from making the same mistakes).

What I did first, was tell a little bit about Grails to explain the team how Grails works. That was actually my first mistake. I should have told them lots, lots, a little more, and everything again after that. I thought the transition would be easy, but they were struggling with the framework and the language. I didn’t expect this, to be honest. My expectation (and experience) is that Grails is easy to start with. Get a book, read the documentation, and your ready to go. We built a good prototype, got great feedback on it! However, the old habit kicked in.

Building Grails
First, we tried to build our Grails application with Maven. Bad idea, since it caused some nasty challenges, like getting the code coverage to appear, and getting come quality metrics with tools like CodeNarc. However, you’ll still have to do your (transitive?) dependency management, releasing of software, reports, etc, so there’s something to say for using Maven. It didn’t quite work for us, however, and we spent quite some time into bending it into something which worked for us, which failed. I still haven’t found a viable alternative to Maven. Gradle is nice, Ivy + Ant/Gant seem okay, but that’s not nowhere near the power (I wouldn’t say flexibility) I got with using Maven. I do not, however, make this a Maven vs Whatever Build Tool discussion. I just happen to like Maven for it’s reports, plugin integration, dependency support and modular structure.

Team
Then I also had to overcome the resistance of some of our team members to dynamic languages. Some people prefer the (fake, IMO) safety a statically typed language provides with it’s compilation process. Well, there’s no helping you if you do an Integer.parseInt(“abc”) in your Java code: it will fail just as badly. At runtime. That’s why we write tests, to cover cases like this. This is true for Java, and it’s just as true for Groovy. However, there was still a lot of FUD about Groovy’s usage in bigger projects regarding refactoring, tool support, and even performance. Well, to be honest: I have no idea how easy it is to refactor Groovy code, but, with less code to write, there’s less to refactor. While this might be a bit short sighted, I feel it holds true for a lot of cases.

IDE
The tool support deserves a paragraph on it’s own. Eclipse + Groovy was not a good combination. At all. It was bad, worse, and even a bit worse than that. Even if you are the genius to get it to work (or would I say madmen, since a genius would choose a tool like NetBean or IntelliJ, or, heck, TextMate), you still wouldn’t be able to run a decent unit test in it. Did I mention refactoring? I didn’t, for a good reason: No Support For Refactoring. Let me rephrase that: No Support For Refactoring… in Eclipse. Then why choose Eclipse, and not a great tool like IntelliJ (I’m referring to the 8 release) or NetBeans you might ask. To be honest: I have no idea. I don’t use Eclipse. I’ve used IntelliJ for the last 5 years, and only recently I’m switching to SpringSource Tool Suite because of JetBrains’ ridiculous decision to not show module dependencies in the project view. I hope they get some rest after the release of IntelliJ 9, and see the light to put it back in. Until that period, STS is a really good substitute, and has excellent Groovy and Grails support, which is getting better each day!

The right approach?
So, if I would introduce Groovy or Grails again at my work, I would:
– Pick the right people. People who are not intimidated by a dynamic language, but who have the discipline to use it right.
– Pick the right people. People who are prepared to make a switch. To switch from IDE, switch from build tool, switch from language.
– Pick the right people. People who have the mentality to make it work, overcome challenges and share their findings.

Conclusion
It wasn’t intentional to put ‘Pick the right people’ there, but I think that this is the critical factor to make it work. Make it work from within the team, and make it work from outside of the team (IT operations, Management, etc). I’m looking forward into hearing your responses to this. I hope it doesn’t sound to bitter, cause I’m not. I just made the wrong choices with a partially not-suitable team. It’s my mistake, and I don’t blame anyone but me. I just hope people can learn from my experiences, and the post from Marc Palmer was just the right incentive to finish this post. I hope it helps!

Read Full Post | Make a Comment ( 12 so far )

Groovy 1.7 Power Assert

Posted on December 11, 2009. Filed under: Groovy | Tags: |

I already mentioned this in my previous post, but I wanted to go a little bit deeper on this: the new Groovy Power Assert (and no, let’s not call is GPA).

Groovy Power Assert makes assertions quite more powerful. The best way to demonstrate is ofcourse by example. When running the following code in Groovy 1.6:

a = 10
b = 9

assert 91 == a * b

This will be your output:

Exception thrown: Expression: (92 == (a * b)). Values: a = 10, b = 9

java.lang.AssertionError: Expression: (92 == (a * b)). Values: a = 10, b = 9
	at ConsoleScript2.run(ConsoleScript2:4)

While quite helpful, Groovy 1.7 introduced an even better assert, which was initially developed for the Spock framework. The new output of running the above in a Groovy 1.7 console is this:

Exception thrown

Assertion failed: 

assert 91 == a * b
          |  | | |
          |  10| 9
          |    90
          false

	at ConsoleScript2.run(ConsoleScript2:4)

Which gives you much more insight in why the assert fails. You don’t have to use numbers, you can use any type of object to assert on, and the assert statement will call the toString method of that class, as demonstrated below:

def names = [ 'erik', 'marcel', 'sebastien' ]
def reverse = names.reverse()

assert ['sebastien', 'erik', 'marcel'] == reverse

Which will output the following:

assert ['sebastien', 'erik', 'marcel'] == reverse
                                       |  |
                                       |  [sebastien, marcel, erik]
                                       false

Quite funky he? Groovy now gives you some nicely formatted assert information which will help you to tackle your failed tests even faster!

PS: (okay, okay, I added this later….) The same works for special Groovy objects, like GPathResults. For example, check the following code:

def xml = new XmlParser().parseText("<test>x</test>")
assert "y" == xml.text()

The result of this:

assert "y" == xml.text()
           |  |   |
           |  |   x
           |  test[attributes={}; value=[x]]
           false

(Mykola, is this what you meant?)

Read Full Post | Make a Comment ( 6 so far )

Gr8 conference in Denmark, 2010

Posted on December 10, 2009. Filed under: Grails, Groovy |

At the 19th and 20th of May 2010,the GR8 conference will be held. From the website: “The GR8 Conference is an affordable conference dedicated to the Groovy dynamic language, the Grails web framework, the Griffon Swing framework, and other great technologies — hence the pun and code name GR8.”. The agenda is not officially known yet, but from good sources I have heard that (ofcourse) Guillaume Laforge will come, as well as know speakers like Andreas Almiray, Mr Haki (from the well known Groovy Goodness series, Sebastian Blank with his iWebkit plugin, Phillippe Delebarre, and many more. With a lineup like this, it’s a conference not to be missed, so checkout the site, which will be open for registration soon, and enjoy some Groovy and Grails quality time in Denmark!!

Read Full Post | Make a Comment ( None so far )

Groovy @Delegate annotation

Posted on December 9, 2009. Filed under: Groovy |

Groovy 1.7 provides some nice new annotations. One of those annotations is the @Delegate. What it essentially does, is providing the methods of the Delegate to the class using the Delegate. This is best explained by a small example:

class Employee {
   def doWork() {  "work!" }
}

class Manager {
   @Delegate Employee employee = new Employee()
}

manager = new Manager()
assert "work!" == manager.doWork()

This works really nice. The Manager now delegates the call for doWork() to the Employee. This is quite powerful, and works really nice and easy.

However, what happens when the Manager has two delegates?

class Cleaner {
   def clean() { "clean" }
   def doWork() { "doWork" }
}

class Employee {
   def doWork() {  "work!" }
}

class Manager {
   @Delegate Cleaner cleaner = new Cleaner()
   @Delegate Employee employee = new Employee()
}

manager = new Manager()

assert "work!" == manager.doWork()
assert "clean" == manager.clean()

This also works really nice. Now the Manager has two delegates, and it can delegate the clean method to the Cleaner, and the doWork method to the Employee. However, since I’m quite curious, and had a small twiscussion with @darthvader42 on this: what happens when the names of the Delegates clash, ie. the Cleaner and Employee both have a method with the same name. This is demonstrated below:

class Cleaner {
   def doWork() { "clean" }
}

class Employee {
   def doWork() {  "work!" }
}

class Manager {
   @Delegate Employee employee = new Employee()
   @Delegate Cleaner cleaner = new Cleaner()
}

manager = new Manager()

assert "work!" == manager.doWork()
assert "clean" == manager.doWork()

This fails! Argh! What happens? The console output is fortunately very clear:


assert "clean" == manager.doWork()
| | |
| | work!
| Manager@2e6a54f9
false

What happened, is that Groovy picked the first Delegate it encountered, and uses those methods. The Cleaner doWork is not called anymore, since all calls to doWork are handled by the Employee.

Conclusion
The @Delegate is a very handy annotation to handle some of the plumbing code for you, but just beware of the results when using more than two @Delegates. Btw, while writing this conclusion, I was also curious what would happen if the Manager itself has a doWork method. As I expected, the doWork method of the Manager takes precedence over that of it’s delegates, so the doWork method of the Manager itself is called!

Read Full Post | Make a Comment ( 4 so far )

Groovy PowerPoint DSL

Posted on February 27, 2009. Filed under: Groovy | Tags: , , |

I’m really not shaving a yak here, but I created a PowerPoint DSL to give a presentation about DSLs! Let’s jump to the code immediately, because if you’re reading this, you must be interested in DSLs.

This is the (Groovy) DSL I wrote:

builder.slideshow(filename:'Test.ppt') {
    slide(title: 'Introduction') {
        bullet(text: 'Bullet 1')
        bullet(text: 'Bullet 2')
    }
    slide(title: 'Slide 2') {
        bullet(text: 'Bullet 3')
        bullet(text: 'Bullet 4')
    }
    slide(title: 'Example') {
        textbox("""This is a slide
With a lot of extra lines
Which make no sense
At all""")
    }
    imageslide(src:'background.png')
}

The DSL is pretty straightforward. I didn’t support all features of PowerPoint (nor would I want to, nor is it feasible), but the basics are here. The DSL currently supports all of the above:

  • Slides with titles
  • Bullets, which can be added to the slides
  • Textboxes, which are large text area’s
  • Imageslides, which are slides consisting of only images. This is to support all the ‘Beyond Bullet Points’ lovers 😉

While the DSL is far from complete (you could add individual images, position them using X,Y coordinates, add tables, add notes and more), the idea is clear: in a consistent and easy to read structure you can define all those elements you need in a powerpoint presentation. All the missing elements, like stated above, can easily be added by adding it to corresponding domain and exporter.

Domain and exporter you say? Yes! There are ofcourse multiple approaches in creating the DSL, but I’ve kept some parts apart from each other. Under the hood, the DSL is transformed into a very simple domain model, also consisting of slides, bullets, textboxes, etc. This extra layer is introduced to create a separation of concerns. Now, the only responsibility of the Builder is to build the domain model, instead of parsing the DSL and also creating the Powerpoint. The creation of the powerpoint is now delegated to a (also) simple Exporter, which understands the API of the POI library used to create the actual PowerPoint file. So, the model is built by the Groovy Builder, and, once the build phase is complete, the model is given to the exporter, which traverses the model. This makes the code cleaner and also allows easy testing of both the DSL and the Exporter. Ofcourse, I tested none, but instead relied on my excellent programming skills……(The next blog is about TDD, okay??)

This resulted in the following diagram:

Application diagram

Application diagram

I like the approach, but if you don’t, or know a better way, please let me know. I’d really appreciate feedback, since I will probably use a similar approach in the next DSL I create.

The code, and the resulting PowerPoint, can be found in the uploaded zipfile. Like I said: as always, let me know what you think!

Read Full Post | Make a Comment ( 5 so far )

Converting Groovy Objects to JSON using Grails

Posted on February 14, 2009. Filed under: Grails, Groovy, Uncategorized | Tags: , , , |

Disclaimer: this might not be the best way to do it. I’m open for improvements, but it’s a way I’m using now, and it works pretty nice!

Currenly, I’m creating an application which does some JSON communication. Since Grails already has nice support for JSON, I wanted to reuse their libraries, but, at the moment, I don’t need a complete web Grails application. So, the plan was to reuse the JSON (deep) converters to convert my Groovy classes to JSON, and work with that. I created the following small test to try to accomplish what I wanted:


import grails.converters.JSON

class Person {
String name = "erik"
int age = 10
}

println new JSON(new Person()).toString()

Well, I don’t think I’d be writing this blog entry if things were really this easy. Executing the above code fails with a nasty NullPointerException:

Caught: org.apache.commons.lang.UnhandledException: java.lang.NullPointerException
	at testjson.run(testjson.groovy:10)
	at testjson.main(testjson.groovy)

Why is this, you might ask. Well, it turns out the JSON converter is using a ConverterUtil class, which expects a GrailsApplication. When there’s no GrailsApplication, the code will fail with a NPE as a result. If you’d like to see this fixed: I’ve created a JIRA issue here.

However, I did came up with a workaround. It’s not perfect, but it works. Since the ConvertUtil is a sort of Singleton, you call it yourself, and set a DummyGrailsApplication instead. Well, instead of the dummy version, we can use a DefaultGrailsApplication instead. So, after our fix, the code looks like this:


import grails.converters.JSON
import org.codehaus.groovy.grails.commons.DefaultGrailsApplication
import org.codehaus.groovy.grails.web.converters.ConverterUtil

class Person {
String name = "erik"
int age = 10
}
ConverterUtil.getInstance().grailsApplication = new DefaultGrailsApplication()
println new JSON(new Person()).toString()

When running this, the following output is produced:

{"age":10,"class":"Person","name":"erik"}

Which is exactly what we want!

Read Full Post | Make a Comment ( 4 so far )

Liked it here?
Why not try sites on the blogroll...