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