Friday, January 18, 2008

DRY Groovy, How To Get Groovy To Import A Class Into a Script

UPDATE: Read to the bottom to see another way to tackle this problem

Each time you repeat yourself in code, you may as well leave a bear trap by your desk. In fact, the bear trap is probably safer for me. Whenever I see repeated code, I want to poke my eyes out. I do my best to keep my code dry whenever reasonable.

So, when I started writing Groovy scripts, it became obvious pretty quickly that I had some utility classes waiting to break out. The only problem was, I couldn't find the technique for importing a Groovy class from another file into the current script. Thanks go to Peter Niederwieser for the solution.

Here's the setup:

Two Groovy files:
c:\tools\groovy\myscript.groovy
c:\tools\groovy\MyClass.groovy

The content of MyClass.groovy:

class MyClass {
def howdy() {
println 'Howdy'
}
}

The content of myscript.groovy:
new MyClass().howdy()


Super simple. However, no matter how I tried to run myscript, I got this error message:
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed,
c:\tools\groovy\myscript.groovy: 1: unable to resolve class MyClass

What gives? The files were right next to each other, but stupid Groovy couldn't find them. That's when Peter reminded me that groovy will look in the classpath to resolve classes.

There are two ways (that I know of) to tell Groovy what your classpath is. You can either indicate it on the command line as in:
groovy -cp c:\tools\groovy myscript.groovy

Or, you can set the CLASSPATH environment variable to include the path where the collaborating class (in this case, MyClass.groovy) lives.

Using the classpath, you don't even have to keep your script and its dependencies in the same directory. I simply set my CLASSPATH, and now I'm off to the races. Now, I keep all my scripts in c:\tools\groovy (which is on my PATH), and my classes in c:\tools\groovy\classes (which is on my CLASSPATH).

WARNING: For all of you Windows users out there, the name of the Groovy file IS CASE SENSITIVE! So, if you want Groovy to find class MyClass, it had better be in something like, %CLASSPATH%\MyClass.groovy. %CLASSPATH%\myclass.groovy did NOT work for me. This would make complete sense to me if I were in a Unix environment. However, I am used to my Windows machines being mostly case insensitive. This is a bit odd, but understandable I guess.

UPDATE: Jochen Theodorou has pointed me in the right direction for another solution that I like better. You don't have to modify the classpath to cause groovy to find the classes that you are importing. Instead, you can add load information to your %GROOVY_HOME%\conf\groovy-starter.conf file. Mine now has these extra lines:
# load classes for local scripts
load c:/tools/groovy/classes

Now, I don't have to keep the CLASSPATH environment variable set and worry about how that interacts with Java.

There you have it. Now, you can keep your scripts dry.

Monday, January 14, 2008

Mocking Groovy Objects with EasyMock in Java

I mentioned before that I needed to do some unit testing of a class that I was targeting in Groovy with come unit tests in Java. In Java, I am using EasyMock to mock out the collaborators. I am dealing with one collaborator, an interface, that looks like this (Groovy):


interface FileSystem {
...
def uploadFile(inputStream, destinationPath)
...
}

For the purposes of this unit test, I didn't care what got returned, so I setup the expectation like this (Java):

desintationFileSystem.uploadFile(streamForFile1, "someDir\\someOtherDir\\file1.jpg");

Running the test, I was greeted with this message:

java.lang.IllegalStateException: missing behavior definition
for the preceeding method call
uploadFile(EasyMock for class java.io.FileInputStream,
"someDir\someOtherDir\file1.jpg")
at org.easymock.internal.MockInvocationHandler.invoke(MockInvocationHandler.java:27)
...

That's when I remembered something fundamental to groovy... the 'def' type means variable return type. For Java, that translates into Object. To make the test run, I either needed to explicitly change the return type on the interface to be void, or simply setup the EasyMock expectation to return a value. Since I didn't want to change the interface, I chose to specify the return value in the expectation.

Sunday, January 13, 2008

How to Cure a Groovy Headache with Java

There was a time during my college years when I was a full-on caffeine addict. I remember once during finals consuming around 10 cans of Dr. Pepper per day. When I decided that I needed to come off the caffeine, I had to use some java (coffee) along the way to avoid the nasty headaches.

Fast forward a few years, and I've once again use some Java to cure a headache. However, today's headache was caused by a mixture of concrete classes and Groovy's seeming inability to mock concrete classes. I wish I knew the Groovy life cycle a bit better to explain exactly why it is that I couldn't mock out java.io.FileInputStream. Suffice to say, Groovy didn't let me substitute in a closure, I didn't want to use mockFor because there was enough else going on. Additionally, Groovy didn't want to cooperate with the EasyMock classextension for reasons I never could quite figure out.

In comes the Java. Since Java and Groovy compile down to the same byte code, testing Groovy with Java is pretty easy. The final solution that I came up with was writing the implementation in Groovy like I wanted to, and writing the test in Java. I simply used org.easymock.classextension.EasyMock to do the mocking, and away we went. This was a nice proof of Java and Groovy living right next to each other and working together. One of the nice things about having the ability to do the test in Java was proving that, indeed, I had all of the project dependencies that I needed and Groovy just did not like mocking out the class.

Watch here soon, and I am going to post a cool little tool that I am working on for spiking the project structure for a setup like this. It's much more stripped down from what Grails will give you. But, if your looking for directory structure and a simple build.gant, then this may be something to look at.

Now, where's my decaf coffee?

Friday, January 11, 2008

Why Do You Use TDD?

After about a year and a half of writing tests before implementation, I'm not sure I will ever go back. Most people call this "Test-Driven Development." However, given the benefits that come from working this way, I prefer the term, "Test-Driven Design."

I use TDD for three reasons - (1) Test-Driven Design forces more loosely coupled code which is much more malleable, (2) I can detect code smells much faster when classes become difficult to test, and (3) it is easier to know when I'm done writing code.

The tests are a nice bonus product of designing code this way, but they are, in fact, not as important to me as the loose coupling and general good design that comes out the other end. When writing tests becomes too difficult, noisy, or lengthy, then something is wrong with the design. Since tests are in place, refactoring to a better design is easier and generally faster. So, this too aids in improving the design of the implementation.

Do the tests get in the way sometimes? Yes. However, this is often a test smell. Perhaps the tests have too much intimate knowledge of the implementation.

If you have not tried writing tests first, I suggest giving it a go on a simple project. Better yet, find someone that is already experienced in TDD and do some pair programming.

Now, go forth and write tests...

Tuesday, January 8, 2008

When Subversion Goes Crazy

Recently, in the midst of a bunch of subversion client updates, some client decided that I was working with ASP.Net files. So, the "SVN_ASP_DOT_NET_HACK" environment variable got set. This causes subversion's directories to be named "_svn" rather than ".svn." This would be great if I needed the feature to prevent ASP.Net from getting confused. However, it turned out to be a royal pain in the rear, and a big confusion for Eclipse. Eclipse does NOT ignore "_svn" files correctly.

It was quite a shock to suddenly see a bunch of _svn folders on one machine, but not another when working with the same repository.