Jeff's Blog

Musings about software development, Java, OO, agile, life, whatever.


Monday, April 28, 2008 
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.





Wednesday, April 23, 2008 
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 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.





Tuesday, April 08, 2008 
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.





Thursday, April 03, 2008 
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 (see http://jlangr.wiki.zoho.com/) 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.





Monday, March 31, 2008 
Upside-Down Problem Solving

In doing Sudoku puzzles, most of the time the next solution is staring you in the face. But you can't see it for all the other numbers in the way.

I got stumped on a puzzle Saturday, one that I'd stared at for about ten minutes without success. I have a ten-minute rule, so it was time for a new tack. (Others might call this ADD, but I follow Weinberg's Bolden Rule: "If you can't fix it, feature it.") I turned the book around to let my son look at it, but continued to look at the upside down numbers. Thirty seconds later, the very obvious solution almost started blinking at me. Duh.

Often, all we need is a different perspective on the problem. Many of us have experienced code enlightenment when having someone read over our shoulder. The usual explanation is that we're now trying to perceive how others are reading our code. Another thought: Sometimes I suspect that a very brief mental break is all that's needed.

But maybe it's just that we're shifting in our chair and catching the code at an odd angle. :-) Next time I'm stumped on code, perhaps I'll invert my display. Or change my font.





Sunday, March 23, 2008 
Dogs and Bugs

My dog kept wandering around the neighborhood, so I recently put up a fence around my back yard. Now I'm experiencing some regret: after all that expense and effort, the dog no longer gets out of the yard! Was it all a waste of time?!!?

(I think Ward Cunningham puts it much more nicely, but hey, I'm not Ward and will never be. Ward says, "How about FIND BUGS PROMPTLY?")





Tuesday, March 04, 2008 
TDD Hype

A trend I've noticed in the software development community is that there are a large number of developers who resist the new wave. Many of those who spent their formative development years doing procedural development went kicking and screaming into the OO age; some suggested that it was an inappropriate tool for many problems. Many C++ developers looked at Java as a toy, not useful for any real work. And I've met enough Java developers who thought that Java was the last word in programming languages.

Certainly we should question newfangled tools and techniques, and insist on putting them through their paces. OO is not the best tool for every problem, Java did suck big time when it first came out, and yet there are now some significant advantages to continue doing business with it. Challenges ultimately help the tools & techniques improve.

Experimentation and innovation is at the heart of the software industry, not active resistance. But it's far easier to sit in a corner and make as many possible excuses for not doing something. I know, because I've done so myself. There are plenty of jobs out there using old technologies, and places where people are happy with the status quo.

So, TDD. Some of us strongly believe in it, only because we've seen benefits firsthand--not just from toy Stack examples, but from working on systems that range from tens of thousands, to hundreds of thousands, and millions of lines of code. Ahh, but the stack example is all the people sitting in the corner see, because that's all they want to believe is behind TDD.

I agree with the vocal dissenters that TDD should not always be used, but not for the lame list of excuses they often come up with. Primarily, the reason is that the typical American software team just isn't that good. TDD is a reasonably tough discipline to get a handle on, and most developers are still struggling with OO, language, and tool basics.

What's interesting is that TDD would ultimately help these people the most--some of its best potential is its use as a learning tool. The vocal dissenters, on the other hand, are usually reasonably sharp developers who already have a good notion of design. Thus they can't quite understand why a technique that promotes more decoupled and cohesive designs is important--"duh, we already get it." Particularly, for example, if they don't happen to work with lots of typically underachieving coders.

Is TDD overhyped? Not a chance. There are still mountains worth of learning that TDD will promote in the minds of the majority of the developers out there. For those who don't want to do TDD, don't do it.

Can TDD be dangerous, and lead to disasters? Yes. This is true for any tool in the wrong hands. That also includes insisting on emphasizing test-after--I've seen that lead to plenty of failures and wasted time. TDD, like OO or any other tool/technique, is not for everyone or every project. But in the right hands, I've seen TDD work wonders on software projects.



RSS Feed (XML)

Archives

February 2004   March 2004   May 2004   September 2004   October 2004   January 2005   February 2005   September 2005   October 2005   November 2005   December 2005   January 2006   February 2006   March 2006   June 2006   August 2006   January 2007   February 2007   March 2007   April 2007   September 2007   October 2007   November 2007   December 2007   January 2008   February 2008   March 2008   April 2008  

This page is powered by Blogger. Isn't yours?