Revisiting BDD in Java

My initial reaction a few years ago to BDD implementations in Java was less than stellar. Since then, I revisited them a couple times, and now I’m digging into them again. They’re still around, so someone must be getting value out of them. I certainly have gotten some mileage around naming and organizing my tests in a more BDD fashion.

Right now, I’m being lazy, and haven’t done diligent research. But my initial internet searches suggest that there are a handful of tools, none of them the de facto standard. I remember my doctor once saying, “We have about a hundred ways to treat this [a plantar wart]. Usually when there are so many ways, it means we don’t know what we’re doing.”

I started looking at one framework in more depth, and coded some straightforward examples. Didn’t seem so bad, until I looked to code a more involved assertion. Here’s one (contrived but simple) example:

Ensure.that(name, and(contains("Langr"), startsWith("J")));

One of the core principles of BDD is “getting the words right.” I think this example demonstrates that sometimes we try too hard, and perhaps this construct isn’t a great idea for Java. The “classic” approach is easily more expressive:

assertTrue(name.contains("Langr") && name.startsWith("J"));

or better…

assertTrue(name.contains("Langr")
assertTrue(name.startsWith("J"));

or even…

assertFirstInitialAndLastName(name, "J", "Langr");

I suppose my complaint could be tempered with the fact that these kinds of compound assertions don’t occur so frequently.

Yes, sure, the failure messages are better. That’s not significant to me, given that I don’t drive my development off of failure messages. Sure, all tests fail at least once, but I usually know why they’re failing the first time, so I don’t need that message initially. Later, when they fail for unknown reasons, more information might be useful (sometimes it is, not always), but if I need that, I just enhance the assertion I already have and rerun the tests. No big deal.

Writing custom “matchers” is also an example in ugliness, given the limitations of Java. (I need to speed up my move to Groovy or Ruby, so I can stop whining about Java so much…)

I won’t give up on the Java BDD tools completely, but I’m not much happier now than I was three or so years ago.

What’s the Next Test?

I coded the “Roman numeral kata” for the first time last night. I thought it was a reasonably straightforward exercise, but then I looked at the solutions of others by searching the web.

In agile, there’s this notion of “doing the simplest thing that could possibly work,” and I think it applies to TDD just fine. It helps keep me in the red-green-refactor rhythm. More importantly, it prevents me from pre-building complexity. It also keeps me in a mode of extreme incrementalism: DSTTCPW keeps teaching me how to truly grow a system incrementally, as agile demands.

From looking at the solutions on the web, however, I suspect that some people translate “do the simplest thing” to “don’t think at all.” Specifically, I’m referring to their progression of tests. At all times, once I complete a single test method, I spend some time thinking about what the next test should be. I don’t spend too much time, but nor do I blindly jump into the next apparently obvious test.

The task in the Roman numeral kata is to convert a positive integer to a Roman numeral. Doing this kata in a TDD fashion, the first test is converting 1 to I, which is a hard-coded return. The second test is converting 2 to II, which is simply done with an if statement. One might refactor at this step to a loop/count construct, or one might wait until 3 (III).

From 3, though, I noted that many of the coders insisted on jumping directly to 4 (IV). Certainly, this works, but most of the solutions I saw derived in this fashion either ended up more complex, or resulted in a fairly excessive solution that scaled back dramatically with some last-step refactoring.

One could argue that this is in the true spirit of incrementalism. After all, we should be able to tackle requirements in any order. Perhaps we need only support the numbers 1 through 4 initially, and later someone will insist on adding 5+.

An argument currently brewing on the XP list goes into the whole YAGNI thing, with one poster suggesting that if you have comprehensive information, there is nothing wrong with taking that into account. Kent Beck subsequently updated his take on YAGNI: “Here’s what I do: consider [forthcoming feature] a little, but try not to get so caught up in it that I freeze.”

In a similar fashion, TDD doesn’t mean “don’t think.” Determining the next test to write should incorporate some thought about what represents the simpler path to a more complete solution. Sometimes this is a guess, but with more experience, the wiser choices are more apparent. Sometimes you make the wrong choice, but you can still end up in the right place, particularly if you refactor with diligence.

With respect to the Roman numeral solution, the better answer is, try 5 (V) before 4 (IV). Then add combinations of V and I (6, 7); then finalize this logic with X, which pretty much demands a table-driven solution.

A last intuitive leap can dramatically improve the solution, but is not essential: Table entries don’t have to represent a single Roman letter. Thus you end up with an entry in the table for 4 (IV), 9 (IX), 40 (XL), 90 (XC), and so on. The logic stays clean and simple:

import java.util.*;

public class Roman {
  private final int number;
  private static final TreeMap<Integer, String> digits = new TreeMap<Integer, String>();
  {
     digits.put(1, "I");
     digits.put(4, "IV");
     digits.put(5, "V");
     digits.put(9, "IX");
     digits.put(10, "X");
     digits.put(40, "XL");
     digits.put(50, "L");
     digits.put(90, "XC");
     digits.put(100, "C");
     digits.put(400, "CD");
     digits.put(500, "D");
     digits.put(900, "CM");
     digits.put(1000, "M");
  }

  public Roman(int number) {
     this.number = number;
  }

  @Override
  public String toString() {
     StringBuilder roman = new StringBuilder();
     int remaining = number;
     for (Map.Entry<Integer,String> entry: digits.descendingMap().entrySet()) {
        int decimalDigit = entry.getKey();
        String romanDigit = entry.getValue();
        while (remaining >= decimalDigit) {
           roman.append(romanDigit);
           remaining -= decimalDigit;
        }
     }
     return roman.toString();
  }
}

If you don’t make the intuitive leap, the final solution is a bit more muddy (as I saw in a few solutions out there). But you have a second chance: Since you have all those wonderful tests, you can refactor the heck out of your muddy solution, looking for a more concise expression, and often you’ll find it.

Clean Code

Uncle Bob Martin just completed a draft of Clean Code, which the publisher site lists as being available August 22, 2008. The book is a code-intensive collection of thoughts on how to keep, well, your code clean. I was honored to submit two chapters, one on “clean classes” and one on emergent design. Uncle Bob got the last word, putting in even more code than I’d laid out on these chapters.

Many of the chapters are contributions by other current-and-ex-Object Mentors, but Bob put in a significant effort to go through the compiled book as a whole, to make sure everything coheres well and put his personal stamp on it.

The announcement got me stoked again about writing. Developer.com is also looking to compile an e-book of my many articles on design patterns (most with a TDD bent), so look for that in the near future. Still, I think it’s time I went back and started on a whole, real book of my own. The C++ tome is still a potential if Mr Koss and I can find mutual time together for it.

Open Source Pairing Scheduler

Rather than whine about not having enough good pairing experiences, I’ve decided to do something about it. Recently I’ve had a few pairing sessions online, and I decided that the software to build would start around the simple notion of scheduling online pairing sessions.

The idea is to slowly start building an online pairing community. I imagine there are many kinds of participants, people who want to:

  • build quality software via pairing and TDD
  • promote their services and ability to mentor via pairing
  • get some work done on a real product
  • get in touch with other members of the agile community
  • learn about either pairing or TDD
  • learn about the effectiveness of distributed pairing
  • learn a specific technology (Java, Rails, JMock, RSpec, etc.)
  • improve their Ward number for bragging purposes

I hope that the scheduler software will be all that and many more. Initially, I created a wiki as a scratch pad area, to help set up sessions, to hold an initial backlog of stories around the scheduler itself, and to record experiences.

I chose Java, but only because of interests in my pairing partner. I’m not sure that the pairing scheduler should be Java, but for now it is. If Java, what represents the best choice for front end (web) technologies?

Please feel welcome to join up and post your recommendations and experiences at the wiki site. Interested developers should send me an email with their intents, and I’ll set up their SourceForge account to have appropriate access.

Atom