Thursday, January 28, 2010

In my last post I commented that sometimes “drinking the Kool Aid” is a bad thing. Here’s an example that bit me for a couple of hours this week.

Groovy and Grails have done a lot to ‘make things work’ by expanding many of the core Java classes to remove the need for all the ‘work’ needed to get something to work. For example, database connections ‘just work’ and you don’t need tons of exception handling code or thinking about how to release them.

Groovy also makes interacting with existing Java code trivial.

However, the combination of the two leads to some problems. Consider my case. I wanted to upload a comma separated value (CSV) file in Grails, split the file apart and build objects from it. Pretty straight forward right? Done it many times in Java with Struts or GWT.

Searching for examples also showed a number of ways to do it. I took the ‘approved’ version from the Grails site.

Searching for ‘groovy csv’ also showed a lot of examples, including the use of CSVReader, which I’ve used before.

Putting the two examples together was trivial and took a few minutes to test and everything went perfect. Until I tried to upload the same file a second time to test the ‘update’ logic. I received an exception, because the file was locked on the host I couldn’t replace the ‘working’ copy.

Turns out that CSVReader is a Java class with very specific lifecycle steps that hadn’t been ‘groovy-fied’ yet. So while Groovy handled all the exception framework, collection logic etc, it didn’t know to close the CSVReader at the end. I added the explicit close() on CSVReader object and things work now.

I was (am?) trying to learn the Groovy paradigm, not just the language so I’m deliberately not writing ‘java in Groovy’. So I didn’t look at exceptions or lifecycle events since for a lot of other ‘common’ thinks Groovy just works. I’ll pay a little more attention to lifecycle from now on.

No comments: