Tuesday, December 16, 2008

Private Bindings in Guice

There are rare occasions when I need to bind something locally in Guice, but I don't want that binding exposed. One such time happened today. Our application uses a Configuration object to hold what we read in from a configuration file. There is plenty of configuration in that file including database connection information and email configuration for reporting errors. Various parts of the application need various parts of the configuration, but nothing really needs the whole ball of wax.

There is, however, one exception to this in our application where a Guice Provider actually does need to have the whole Configuration object. So, we need to have a singleton Configuration instance bound, but I still don't want that exposed.

Enter annotated bindings. Guice allows you to bind the same type more than once and to distinguish the different bindings by adding an annotation. The annotation gets added to the binding in the module as well as the location where the injection is to occur. So, in this case, we have a binding and Provider like so:


bind(Configuration.class).annotatedWith(DontExpose.class).toInstance(privateConfig);
bind(Foo.class).toProvider(FooProvider.class);

private static class FooProvider implements Provider {
public FooProvider(@DontExpose Configuration config) {
...
}
}


The binding is placed in the configure() method of the Guide Module, and the FooProvider is a private static within the same Guice Module class. Unless you take one extra step, however, this binding is still exposed.


Normally, my binding annotations are publicly defined within the project. Any class that Guice builds can ask for a Configuration annotated with @DontExpose. To keep that from happening, we simply define the @DontExpose binding annotation as a private element within the Guice Module. So, the final module would look something like this:


import com.google.inject.*;
import java.lang.annotation.*;
import org.apache.commons.configuration.*;

public class TestModuleShouldBeDeleted extends AbstractModule {

private final CompositeConfiguration config;

public TestModuleShouldBeDeleted(CompositeConfiguration config) {
this.config = config;
}

@Override
protected void configure() {
bind(Configuration.class).annotatedWith(DontExpose.class).toInstance(config);
bind(Foo.class).toProvider(FooProvider.class);
}

@Retention(RetentionPolicy.RUNTIME)
@Target( { ElementType.FIELD, ElementType.PARAMETER })
@BindingAnnotation
private @interface DontExpose {
// marker annotation
}

private static class FooProvider implements Provider {

private final Configuration configuration;

@Inject
public FooProvider(@DontExpose
Configuration configuration) {
this.configuration = configuration;
}

@Override
public Foo get() {
return new Foo(configuration.getString("foo.value"));
}
}
}


Now, the binding to Foo is exposed (as we want it to be), but the binding to the Configuration is not. This isn't a pattern I use very often, but it was useful today.

Monday, December 15, 2008

Why I Don't Use "Given, When, Then"

In Introducing BDD, Dan North states that he and Chris Matts were trying to develop a template that, "had to be loose enough that it wouldn’t feel artificial or constraining to analysts but structured enough that we could break the story into its constituent fragments and automate them." This gave birth to Given, When, Then syntax. One example that is given in the article is:

Given the account is in credit
And the card is valid
And the dispenser contains cash
When the customer requests cash
Then ensure the account is debited
And ensure cash is dispensed
And ensure the card is returned

This certainly has structure. But, I personally feel this is still a bit too artificial. Perhaps it is the large amount of content related to the context (account is in credit, the card is valid, the dispenser contains cash). I try to avoid specifying behaviors that have this many moving parts. I would prefer to see a behavior like:

The dispenser when the account is in credit should dispense cash.
The dispenser when the account is in credit should debit the account.
The dispenser when all transactions are complete should ensure the card is returned

I want to read sentences. When possible, I want to read short sentences. Given When Then generates a matrix of sentences to be parsed. GWT also saves some space in the report, but I gladly give that space back to have behavioral sentences that are easier to read quickly.

So, how do I keep the language regular and well-formed? The answer shows up more in the source code of the behvaiors than in the report. So, I might write the following behavior using EasySpec (in Groovy):


@EasySpec(interest='The dispenser')
class Dispenser_happy_path_Test extends GroovyTestCase() {

def account = new Account(balance:1000)
def dispenser = new Dispenser(available:5000)

@Context('when the account is in credit and the dispenser has cash')
public void setUp() {
dispenser.dispense(account, 100)
}

@Behavior
void test_should_debit_the_account() {
assertEquals(900, account.balance)
}

@Behavior
void test_should_dispense_the_requested_cash() {
assertEquals(100, dispenser.totalDespensed)
assertEquals(4900, dispenser.available)
}

@Behavior
void test_should_return_the_card() {
assertTrue(dispenser.lastCardReturned)
}
}

Upon running the EasySpec report, the user will get the following behaviors:


The dispenser when the account is in credit and the dispenser has cash should debit the account

The dispenser when the account is in credit and the dispenser has cash should dispense the requested cash

The dispenser when the account is in credit and the dispenser has cash should return the card


Easy Spec actually generates reports with nice formatting like this.

Perhaps all of this is just personal preference. But, I do find it easy to go back to old specifications and understand what is going on. Language and fluency are important.

You Might Be A Behaviorist...

Are you doing BDD? This is a question I've often heard at recent conferences. As far as I can tell, most people that have looked at BDD concepts are quite sure if they're doing BDD or not. Here are some sign that you might be a Behaviorist:

  1. You talk more about executable specifications and less about "tests."
  2. You write your specifications before you write the production code.
  3. You place high value on natural language in your tests.
  4. You can generate a system-wide report that shows system behaviors in natural language. Bonus points if you do this with every build.
  5. You write your specifications or tests with exactly one context per test class.
Not everyone that is doing these things would classify their projects as using BDD. And, not everyone that says they're using BDD is applying these concepts. But, I think that in the majority of cases you will find a majority of these practices in some form or another.

If I have missed anything, Dear Reader, please let me know.

My English Teacher Would Be Proud -- Proper Language Is Still Important

My high school had one English teacher that was dreaded by all, Mrs. Koch. Mrs. Koch's classes were known to be tough. Most of my friends were accustomed to getting high grades, but this didn't happen too often in Mrs. Koch's classes. Over the course of two semesters, one student got an 'A' in one semester. Mrs. Koch took for granted that we knew the basics that we were supposed to know. For written assignments, she assumed that everything would be spelled correctly and there would be zero grammatical errors. Assignments were graded for content, but grammatical errors caused sever markdowns in one's grade. Language was important.

I am thankful to Mrs. Koch for nurturing a strong sense of grammar in me. Perhaps this is what I have always liked the strict syntax of programming languages. This may also explain why I like Behavior Driven Development so much. Language was critical in Mrs. Koch's class, and language is critical to understanding business software.

BDD brings language into what I believe is its proper place -- the forefront. Language allows developers to understand the business. Language allows the development team to communicate with the project sponsors and domain experts. The more prominent, clear, and accessible our language is, the more readily we understand each other. The more accessible the language is in the code base, the easier it is to understand what we are doing and why we are doing it.

This is why I like BDD so much. When I read through specifications, I can understand what the system does. The more natural the language is, the faster I can stop thinking about syntax and start thinking about the correctness of the system. Natural language also helps to engage the non-developers on the team. While I've watched our project managers look at Java code and guess about what the system is doing, its much easier for us to have a conversation without Java language constructs getting in the way. Likewise, the less we talk about exceptions, try/catch blocks, and if-else statements, the better. Instead, we prefer discussing how the system should and should not behave under certain conditions.

Case in point: Instead of, "The protected area should thrown an exception for unauthenticated users," I would prefer to say, "The protected page should require the user to be logged in." We shouldn't have to acclimate the business types to programmer speak.

Clear language also helps us identity when the design is going astray. One simple word is often a clue to me that a class has too much responsibility. That magic word is, "and." Here's an example:

Lets assume that we're developing a console application that takes in a relatively complex configuration file. The customer has told us that, when the configuration is bad, he wants to be notified in a variety of ways. Sometimes this process will be run manually, and he would like the operator to receive immediate console output for bad configuration. Sometimes, the process is launched automatically and unattended, so he would like configuration problems to be emailed as well. For a final good measure, he has also requested that problems be logged to the logging system we have chosen for the project. We'll assume that the logging and email services live behind a nice interface that is easy to test. We might, then, get a specification that looks like this

The ConfigurationHandler, when some configuration properties are missing and logging is configured and email is configured should log an error for the missing properties and send an email for the error and write an error message to the console.

Assuming that our logging and email systems are properly testable (injected somehow), the actual calls to those services could be a pretty small footprint in the production code. However, this is too much responsibility for the ConfigurationHandler. We see it logging, sending email, printing to the console and killing the process somehow. There are lots of "ands" in the specification indicating that perhaps too much responsibility has been given to the ConfigurationHandler.

If we look at the behaviors shown, they are all about reporting the error. This is when we notice that, perhaps what we need is one more concept called the ErrorService. We can hide all the emailing and logging behind that. So, we break out a new class and a new interface and we end up with the following specifications:

The Configuration Handler, when some configuration properties are missing should report the missing properties to the ErrorService.

The ErrorService should forward errors to the log file, email, and console.


There are still some "and's" there, but the responsibilities are better broken down.

Language is critical to understanding software. BDD helps bring language into more prominence. What does the language of your specifications tell you?

Package Properly: Where Your Tests Live Is Important

About nine months ago, our team decided to start using Behavior Driven Design. Rather than making big changes in the build system to bring in a BDD framework, I put together a BDD reporting framework called EasySpec that allowed us to continue to leverage JUnit. One of our goals in trying BDD was to really push the limits of natural language in testing and determine what the limits were for BDD. We ran into limits with our mocking framework, but Mockito solved those problems for us (more on that in a future post).

One thing that we found was that BDD works pretty well for all levels of testing. Many of the BDD practitioners will only use BDD for higher level integration testing. However, I've found that I really like it for unit-level testing as well. Language is important regardless of where. It is certainly nice to understand system behavior in the large, but as a developer I need to understand behavior in the small as well.

We package our unit-level tests in a test source tree that parallels the production code source tree. So, if I am spec'ing out the com.company.foo.NewFoo, then the production source lives in myProject/src/com/company/foo/NewFoo.java and the first spec will end up in myProject/test/com/company/foo/NewFoo_when_X_Test.java.

One unintended advantage of staying with JUnit and EasySpec was that our new BDD tests landed right next to the old JUnit tests. The subconscious communication that this packaging created was wonderful. It removes the step of questioning where the next test or spec should live. The next spec goes into the parallel package. This also communicates that we are going to be driving the same requirements with BDD that we drove previously using TDD methods. In other words, we aren't just writing larger integration tests with BDD. We are writing as much as possible using BDD because again, langauge is paramount to understanding the system.

How do you package your specs? And, have you pushed the limits to find out how low-level you can drive BDD concepts into your design? I love designing in the small with BDD. My production code is better, and the specification artifacts are wonderful. When supporting code writting six months ago, I find it much easier to understand the system if we have EasySpec specifications rather than JUnit tests -- regardless of the level of abstraction under test.

Thursday, December 11, 2008

Publishing Build Artifacts With Hudson

Tonight, I found yet another reason to love the Hudson continuous integration server. Publishing build artifacts is way easy. What's better, the latest artifacts are available under a static link. So, it's easy to set a bookmark and always have the latest output available without digging through the server.

I've setup publicly visible builds for EasySpec along with the Groovy example and Java example projects. All of these projects use EasySpec for Behavior Driven Design. A major component of BDD is having the latest behavior report available. So, I have included a build target named "report" in each of these projects. This target simply runs EasySpec to generate the behavior report into a known location in the workspace.

Let's take the Groovy example and walk through it. After every checkin, the Hudson build does

gant clean test report

This cleans the working copy, then compiles everything, runs the tests, and finally generated the EasySpec report. Relative to the working copy base, the report ends up in build_output/reports/EasySpec/index.html

To publish this report, only a couple of simple steps are required. First, go to the project configuration page for the build that you wish to publish artifacts from. In this case, that's Hudson/GroovyExample/Configure. Then, find the checkbox, "Post-build Actions / Archive the artifacts" Enter the relative path of the artifacts that you wish to publish. In this case, that's "
build_output/reports/EasySpec/index.html" Click "Save" and it's all done.

Now, everytime this project builds successfully, the latest EasySpec report is published to a constant URL. If you want, checkout the latest example EasySpec report.

I love Hudson

Sunday, November 30, 2008

EasySpec Continuous Integration Server Visible

I have made available a Hudson build for EasySpec. This turned out to be a fun exercise in setting up Hudson to build a GoogleCode project and a Gant project all in one. The Hudson plug-ins for GoogleCode and Gant both helped a great deal.

URL: hudson.testinfected.net

Hudson and .Net

Hudson has to be the easiest CI server I've ever worked with. And, based on the number of plug-ins and the rate at which plug-ins are being developed, it must have a pretty easy plug-in model. Apparently, the gant plug-in took about an hour to write.

Configuration is very easy as well. I don't believe I've ever had to dig into the actual configuration files for different builds and tasks. The web front-end for configuration is great. I also like the ability to watch the console during a build and all of the build status tracking and archiving. There are MANY more great plug-ins available, many of which would be applicable to .Net projects as well as Java projects.

Although I'm not doing much .Net development right now, if I was, I would probably be tempted to setup a Hudson CI server to see if I liked it better than CC.Net. For those readers that are interested in seeing more about using Hudson with .Net, Redsolo has a pretty comprehensive guide to getting started.

Check it out.

Thursday, August 28, 2008

GMail + Address - Why Duplicated Logic Is Still A Bad Idea

If you use GMail, you probably already know that you have an infinite number of addresses with a single account. You can add periods wherever you like in the address. You can also add tags to the address using the '+' symbol. So, foobar@gmail.com, foo.bar@gmail.com, fo.obar+baz@gmail.com all go to the same place.

I like using the '+' tags when giving out my email to automated systems and signups. This makes it easy to determine if someone is handing out my address for spam when I haven't agreed to that.

Here's the duplicated logic part:

So, a while back I activated a subscription for MSDN. I used my.address+msdn@gmail.com for the email address. Today, I needeed to download something, and I went to login again, and the system is behaving like I don't remember the password. This is possible, but unlikely since the passwords that I tend to use (1) I remember, and (2) fit most all password schemes. However, I conceded that, perhaps, I don't remember the password. When I go to enter the email address for password retrieval, I get a validation error stating that the email address that I entered is malformed. Funny, MSDN didn't have any trouble sending the email to that address. I tried with the +msdn, and of course, that yielded a validation error stating that the email address was not in the system.

And, yes, I did go back to the confirmation email, and they DID send it to the ...+msdn@gmail.com address. So, that is, in fact, the address that I registered with.

It's obvious what's going on here. The registration site gleefully accepted an email address that the password retrieval site refuses to accept as a well-formed address. The logic for what constitutes an email address has been duplicated. Perhaps at some point they were the same. The registration site may have been "enhanced" to allow the '+' addresses, or perhaps the lost password site was "fixed" to only allow certain formats of email address. Regardless, it now rests as one system with different rules for what is and is not valid.

Furthermore, this leads me to suspect that the login site actually shares the same rules with the lost password site. Meaning, I was able to register with an email address that I cannot login with.

Looks like I'll have to talk with a human to get this sorted out tomorrow. Figures that I would find it thirty minutes after everyone goes home.

Saturday, June 28, 2008

How Well Do You Know Your Tool?

Have you ever used a great tool? I've been doing some woodworking lately. So, I've been thinking a bunch about tools. There is nothing like having a good tool when you need it. Among tradesmen, tools (and tool brands) can evoke a great deal of passion. You may have know a "DeWalt guy" or a "Matco" lover.

My grandfather was a very skilled woodworker. He took a great deal of pride in crafting fine pieces of furniture that were beautifully finished. My grandfather was a Craftsman guy. Even when offered more expensive tools, he preferred to work with Craftsman. Perhaps the source of his passion was the good service he got from the local Sears, or perhaps it was because the tools had never let him down. Regardless of why, he was passionate about his tools.

Software development tools are no different. One need look no further than the vi / emacs wars fought at countless water coolers (to this day) to see the passion that one can have in a development tool. In Java-land, you may be an Eclipse or IntelliJ devotee. In .Net, you may insist on running ReSharper or CodeRush. All of this passion is useless without one critical component...

How well do you know your IDE? When was the last time that you looked through the feature shortcuts? When was the last time that you looked through release notes for new versions? What about learning keyboard shortcuts?

I primarily learn new features two ways. I pick up tricks from my teammates when pair programming. Sometimes, I learn things completely by accident. Every once in a while, I fat-finger a keyboard shortcut, and something really cool happens. Typically, it's not a feature that I want at the time, but it's new to me. To help me remember it, I will practice it a few times, and share the new information with the rest of the team.

Take some time and read up on your IDE. Good tools are useless if you swing everything like a hammer.

Wednesday, June 11, 2008

Running Fitnesse Tests

It is possible to execute a FitNesse page as a test, even when it is not marked as a test. This is a good thing. Say that you have a page that resides at:

http://localhost:8181/MySuite.MyTest

You can simply execute that test by appending "?test" to the end of the URL. Likewise, you can execute the page as a suite by placing "?suite" at the end of the URL.

In our project, we have some pages that are common to all tests. In order to prevent those pages being executed as tests, we changed the page property to indicate that they are not tests. However, it is occasionally useful to execute those pages by themselves for debugging purposes. Rather than going through the annoyance of setting the "Test" property and hoping that I remember to clear it, I can just append the magic text to the end of the URL, and I'm off to the races.

Friday, May 30, 2008

Agile Austin Open Space

The Agile Austin Open Space kicks off this evening with agenda and topic setting. You can find the proceedings documented on the wiki at: openspace.agileaustin.org

I will be blogging about proceedings as I see things interesting. Be sure to watch the wiki.

Wednesday, May 28, 2008

Why Behavior Driven Development?

Two years ago, I became completely test-infected. I hate writing implementation code without writing the test first. Then, about six months ago, I was introduced to Behavior Driven Development (BDD). I liked what I saw, but I really didn't see any tools that I wanted to bring into our build system. The last thing that I wanted to introduce to the company was another test framework. JUnit was meeting our needs fairly well, and we were already using FitNesse on our team whereas the rest of the company was not. We didn't want to add another tool on top of that.

Then, a few months ago, I saw Scott Bellware give a talk on BDD and saw how he simply did BDD within a normal unit-testing framework and used .Net attributes to markup the tests with the BDD language. I liked what I saw. That night, I started a similar tool for JUnit called EasySpec. The tool still has some kinks to work out, but BDD has definitely brought some interesting insights into how we design our tests.

So, why BDD? At first, it was simply a trial of a style that seemed to do a good job of pulling out the Ubiquitous Language. Now that we have been using the techniques for about three months, I must say that I really like using BDD for creating software -- especially around the Domain Model.

BDD cleans up the language and gets the developers talking more about behaviors and less about implementation. Where, in the past, I might have been tempted to write a test with a method name like, "the_service_should_throw_an_exception_if_the_user_is_not_authenticated," I would now write that same test with a name like, "the_service_should_require_authenticated_users." Internally, the test would still be implemented in the same fashion, with probably the same code. However, language is important. It's important for the developers to think in the domain rather than hiding in the implementation layer. If I'm interested in the details of how the service requires authenticated users, then I can look at the details of the test (which should still be cleanly written) and see that in fact, the service will throw an exception if it somehow is handed an unauthenticated user.

This is merely one example. Keep a watch here for more information about BDD and why I'm hooked. Also, I should be putting some polish into EasySpec in the next week or two so that it's more user-friendly. If you're already using JUnit, and you want to try out BDD, take a look at EasySpec.

Friday, March 14, 2008

EasySpec in the works

I have started a new project named EasySpec for doing Behavior Driven Development in Java and Groovy. There is plenty of functionality that I want to add soon, but the core of it is available (as a .jar). The project page on GoogleCode can be found at http://code.google.com/p/easyspec/.

Our team has been using EasySpec for guiding our behavioral specifications for the last three months. I am hooked. If you want specific examples, leave some feedback here. I should be finishing up the current feature development within the next day or so. Then, I will be finishing some examples to be posted by the end of next week.

Create a Guice Injector Using Multiple Modules

This is a very short note, but I spent too much time on Google looking for this answer and I wanted to provide a concise bit of information about it. It has recently become necessary for us to separate our Guice configuration into multiple Guice modules. We tend to have some dependencies that are project specific and others that typically remain constant from one project to another. I didn't see mention of this in the Guice guide. So, here is the information:

Guice.createInjector() can take a variable number of Modules. So, it is trivial to do this:

Guice.createInjector(myProjectDependencies, myDatabaseDependencies) and so on.

This will really help to prevent duplicating binding logic from one project to the next. We are separating our data-tier module out from project-specific bindings.

Again, all of this is trivial, but since I didn't readily find the answer on Google earlier, I wanted to put it out.

Another interesting note is that it is possible to bind to classes in module A that need bindings from module B while at the same time bind to classes in module B that need bindings from module A. Very slick.

Friday, February 8, 2008

How To Quickly Frustrate Future Developers

Simply put, if you want to frustrate your teammates, let your abstractions leak.

Have a production implementation of an interface with stubbed calls? How about a subclass that neuters parent-class functionality? If you do, you may be well on your way to setting a trap for future developers (quite possibly your future-self).

Interfaces
If you really don't need all the methods on an interface, then the interface is too big and should be broken out. Here's a contrived example. Consider what an IDaddy interface might look like:


interface IDaddy {
public void changeDiaper(Baby baby);
public void procreate(IMommy mommy);
//More methods, but significantly less than the IMommy interface.
}

This interface had better have a singleton production interface. Otherwise, other implementations of IDaddy that implement the procreate(IMommy) will have some serious 'splaining to do! (IMommy better be a singleton as well, or the IDaddy is in big trouble...).

Anyway, there are certainly uses for having someone other than Daddy change the baby diaper. Perhaps a better set of interfaces would be:

interface IBabySitter {
public void changeDiaper(Baby baby);
}

interface IDaddy extends IBabySitter {
public void procreate(IMommy mommy);
}

Now we can have several implementations that can change the baby diaper without creating family strife!

Subclasses
Just ran into this class today:

public class UnknownColumnNameException extends RuntimeException {

private static final long serialVersionUID = 1L;

String strColumnName;

public UnknownColumnNameException(String colName) {
strColumnName = colName;
}

public String toString() {
return super.toString() + " ColumnName = " + strColumnName;
}

public void printStackTrace() {
System.err.println(" ColumnName = " + strColumnName);
super.printStackTrace();
}

public String getColumnName() {
return strColumnName;
}

For those of you not completely familiar with Java's exceptions, you may not notice what is missing. In the top level processing, we have a generic, last-ditch catch of all Throwable so that we can dump log files, etc. This exception has not set any message. So, when I do an ex.getMessage() in the top-level catch, all I get is null. Thanks for nuthin'.

The user has to know about this specific exception type in order to get the useful information back out of it. Bad, Bad, Bad! If this pattern was extended, then we'd have to put a catch for each type of exception that just might happen, and pull the specialized information out of each one. Forget it!

The fix? Simply set the message in the subclass. In this case, this can be done by leaning on the superclass constructor as follows:

public class UnknownColumnNameException extends RuntimeException {
...
public UnknownColumnNameException(String colName) {
super("Could not find column with name '" + colName + "'.");
strColumnName = colName;
}


Simple fix. Great improvement in usability. Perhaps next time, I won't have to resort to the debugger to know that the input file has a problem.

What kind of abstraction leaks have you found?

Tuesday, February 5, 2008

How Can a Simple Code Template Change Make Life Better?

Ever felt like making a small change has sent you down a rabbit hole? I sure have. Consider the following classes:


public interface NotificationService {
void sendNotification(String user);
}

public class Unit {
private NotificationService notification;

public Unit(NotificationService notification) {
this.notification = notification;
}

public void doSomething(String username) {
notification.sendNotification(username);
}
}


You might write a test to ensure that Unit.doSomething() passes off the username to the NotificationService.sendNotification(). This would be a very simple mock test.

Now, let's assume that everything shown so far is already under test, 100% coverage. Requirements have changed, and now when we doSomething(), we should check for pending notifications for that username first.

The first change to make would be adding a method to the NotificationService interface:


public interface NotificationService {
void sendNotification(String user);
Notifications retrievePendingNotifications(String user);
}


Now, we can write a test for the Unit class, using a mock of NotificationService to verify that doSomething() will check for the pending notificiations. Doing Test-Driven Design, we want to make sure that we are focusing on changing one class at a time. However, now that we have added retrievePendingNotifications() to the interface without actually implementing that method on the implementing classes, we will have a compile error.

One choice for getting around this would be to go down the rabbit trail, writing tests for the implementing classes and actually implementing the new method. Personally, I don't like to do this because it changes my focus. I would rather first ensure that the caller is correct before worrying about the actual implementation of the interface.

Most modern IDE's will offer a quick-fix to stub out the implementation of the interface so that things will compile. The default behavior for this default implementation is typically to return the simplest thing possible. If the function is void, then the stubbed method does nothing. If the function returns a primitive, say int, then the IDE will put in something like return 0; to make things compile.

This kind of default stub has already worried me that I will forget to actually do the implementation. In fact, I have done just that before, sometimes not finding the hole until a day or two later. At that point, figuring things out sometimes involves going to the debugger to figure out why I'm getting a NullPointerException.

Enter code templates. The default implementation can be modified in most IDE's. Here is a sample of how I changed my code template to prevent this problem in the future:


public Notifications retrievePendingNotifications(String user) {
throw new NotImplementedException(
"NotificationServiceImpl.retrievePendingNotifications() not yet implemented.");
}


Now, I don't have to try and keep that little piece of information in my head. I can rest easy that, if I forget to implement something, it will still fail (hard) during integration testing. Now, I will know the direct cause of the problem immediately.

It's amazing to me how this simple change has made me rest so much easier.

Go forth and write tests!

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.