Stephen Freeman Rotating Header Image

Coding

Notes on the craft of programming

Java synchronisation bug on OS/X?

I’ve come across what might be a synchronisation bug while working on the book.

The end-to-end tests for our example application use the WindowLicker framework to drive the Swing user interface. Our test infrastructure starts the application up in another thread (it’s as close as we can get to running from the command line), then creates a WindowLicker driver which, eventually, creates a Java AWT Robot. It turns out (we think) that this means that we have two threads trying to load and initialise the AWT library in parallel, which hangs. Our workaround is to call a delaying method before creating the WindowLicker Driver:

private void
makeSureAwtIsLoadedBeforeStartingTheDriverOnOSXToStopDeadlock() {
  try {
    SwingUtilities.invokeAndWait(
      new Runnable() { public void run() {} });
  } catch (Exception e) {
    throw new Defect(e);
  }
}

That’s not really what invokeAndWait() is for, but it solves our problem until we can find a better answer, and we hope that the hack is at least self-explanatory.

Does anyone have a better explanation or fix? OS/X 10.5.6, Java 1.5.0_16, White MacBook 2.4 GHz Intel Core Duo. Nat‘s Linux installation works fine.

Mock Roles not Objects, live and in person.

At the recent Software Craftsmanship conference in London, Willem and Marc ran a session on Responsibility-Driven Development with Mocks for about 30 people. Nat Pryce and I were sitting at the back watching and occasionally heckling.

The first striking thing was that when Willem and Marc asked who was using “Mock Objects” most everyone put their hand up (which was nice), but then only a handful also said they were thinking about Roles and Responsibilities when they did (which was frustrating). We first wrote up these ideas in our paper “Mock Roles Not Objects” and much of the difficulty we see people have with the technique of Mock Objects comes from focussing on classes rather than relationships.

As it happens, an example popped up in the rest of the session, which was run as a Coding Dojo. What was interesting to me was how the group managed to turn around its design ideas. Here’s what I can remember about how it worked out.

The domain was some kind of game, with a hero who moves around an environment slaying dragons and so forth. The first couple of stories were to do with displaying the current room, and then moving from one room to another. It was a little difficult getting started because the limitations of the event didn’t allow enough time to really drive the design from outer-level requirements, but the group managed to get started with something like:

describe Hero do
  it "should describe its surroundings" do
    hero = Hero.new(room)

    room.stub!(:description).and_return("a room with twisty passages")

    console.should_receive(:show).with("in a room with twisty passages")
    hero.look(console)
  end
end

The expectation here says that when looking, the hero should write a text describing the room to the console. This was a place to start, but it doesn’t look right. Why is a hero attached to a room? And hero.look(console) just doesn’t read well, it’s hard to tell what it means. The tensions became clearer with the next feature, which was to have the hero move from one room to another. If we write

hero.move_to(other_room)

how can we tell that this has worked? We could ask the hero to look() again, but that means making an extra call for testing, which is not related to the intent of the test. We could ask the hero what his current room is, but that’s starting to leak into Asking rather than Telling. There may be a need for the hero to hold on to his current location, but we haven’t seen it yet.

Suddenly, it became clear that the dependencies were wrong. We already have a feature that can be told about the hero’s situation, which we can build on. If the feature were to be told about what is happening to the hero, we could use that to detect the change in room. So, our example now becomes:

describe Hero do
  it "should move to a room" do
    hero = Hero.new(console)

    room.stub!(:description).and_return("a room with twisty passages")

    console.should_receive(:show).with("in a room with twisty passages")

    hero.move_to(room)
  end
end

That’s better, but it’s not finished. The term Console sounds like an implementation, not a role. Most of the sword-wielding adventurers that I know don’t know how to work a Console, but they’re quite happy to tell of their great deeds to, say, a Narrator (as David Peterson suggested). If we adjust our example we get.

describe Hero do
  it "should move to a room" do
    hero = Hero.new(narrator)

    room.stub!(:description).and_return("a room with twisty passages")

    narrator.should_receive(:says).with("in a room with twisty passages")

    hero.move_to(room)
  end
end

The whole example now reads as if it’s in the same domain, in the language of a D&D game. It doesn’t refer to implementation details such as a Console—we might see that code when we get to the detailed implementation of a Narrator. Obviously, there’s a lot more we could do, for a start I’d like to see more structured messages between Hero and Narrator, but the session ran out of time at about this point.

Some lessons:

  1. Naming, naming, naming. It’s the most important thing. A coherent unit of code should have a coherent vocabulary, it should read well. If not, I’m probably mixing concepts which will make the code harder to understand and more brittle to change than it needs to be.
  2. When I’m about to write a test, I ask “if this were to work, who would know”. That’s the most revealing question in B/TDD. If there’s no visible effect from an event, except perhaps for changing a field in the target object, then maybe it’s worth waiting until there is a visible effect, or maybe there’s a concept missing, or maybe the structure isn’t quite right. Before writing more code, I try to make sure I understand its motivation.

Willem’s (and many other people’s) approach is slightly different. He likes to explore a bit further with the code before really sorting out the names, and he’s right that there’s a risk of Analysis-Paralysis. I do that occasionally, but my experience is that the effort of being really picky at this stage forces me to be clearer about what I’m trying to achieve, to ask those questions I really ought to have answers to, before I get in too deep.

SOLID Development Principles – In Motivational Pictures

Excellent series of images from Derick Bailey. Here’s an example:

Single Responsibility Principle

Just because you can, doesn’t mean you should.

SingleResponsibilityPrinciple

RT @Jtf

Expressiveness makes the difference

I was chatting with Keith about what the Software Craftsmanship event should really be about, in the context of a discussion of whether some of Jason Gorman’s list of guitar heroes are actually worth listening to (you still with me?) 1.

The next obscure piece of evidence is Maurice Murphy’s YouTube masterclass. For those who don’t know, Maurice Murphy has been Principal Trumpet in the London Symphony Orchestra for years (nerds without an interest in orchestral music will nonetheless have heard him on the Star Wars sound tracks). What’s interesting about the video is that what they emphasise most is being musical, making sense of the melody. They have no interest in pyrotechnics and assume that the student knows the basics.

The (barely sustainable) link with master-level coding and performance, we realised, is that both are about being expressive. The master coder/performer has a point of view and they use their considerable technical skills to get it across. The code that really impresses me is almost entirely about the domain, it just reads well. Most of the code most of us see, however, is stuck a level below, I have to read through the implementation to get to the meaning.

Years ago an old friend of mine said that when she first started going to conferences she wouldn’t be impressed by some of the big names because what they said was obvious. Later, she learned that being obvious can be really hard.


1) Disclaimer I never was into rock guitar heroes, so Jason’s post was a bit academic for me.

Unpack the bag

There’s a common pattern where an object is constructed with a Context object that carries all the dependencies the new object might need. It’s often used, for example, with classes that package up domain behaviour based on lower-level services, something like this:

public class PriceReconciler {
  private final Context context;

  public PriceReconciler(Context context) {
    this.context = context;
  }

  public boolean isAvailable(Item item, Price price) {
     Location location =
        context.getLocationFinder().findLocationFor(item);
     SKU sku = location.lookup(item);
     return context.getCurrencyConverter()
                        .compare(price, sku.cost()) < 0;
  }
 // and so on...
}

Mary Poppins

Over time the Context gets used in more and more places, and acquires more and more contents to carry around. It starts to feel like Mary Poppins' carpet bag (there's an old cultural reference) that contains a roomful of furniture. When everything is available everywhere then developers will use what they have in scope and, pretty soon, there are implicit dependencies all over the domain layer.

A while ago, I was working with a class that used one of these context objects. The class was quite large so, to help us understand it, my pair and I extracted the services it used into fields:

public class PriceReconciler {
  private final LocationFinder locationFinder;
  private final CurrencyConverter currencyConverter;
  private final LooseChangeCollector looseChangeCollector;

  public PriceReconciler(Context context) {
    this.locationFinder = context.getLocationFinder();
    this.currencyConverter = context.getCurrencyConverter();
    this.looseChangeCollector =
      context.getLooseChangeCollector();
  }
 // and so on...
}

Doing this made clear that the class used only three of the many services available on the context. More interesting, it showed that the looseChangeCollector was only used once, in a method that turned out to be referenced just once—by a class that also had access to the context. Our extraction highlighted that this behaviour was in the wrong place, it didn't really have a relationship with the rest of PriceReconciler, so we moved it to its calling object and simplified the PriceReconciler. With just two dependencies, our
next step was to set them directly in the constructor

public class PriceReconciler {
  private final LocationFinder locationFinder;
  private final CurrencyConverter currencyConverter;

  public PriceReconciler(LocationFinder locationFinder,
                         CurrencyConverter currencyConverter)
 {
    this.locationFinder = locationFinder;
    this.currencyConverter = currencyConverter;
  }
 // and so on...
}

which made the PriceReconclier just a little easier to reuse since we'd narrowed its dependencies.

Kent Beck wrote recently about this tension between being concrete and abstract parameters. There obviously isn't a single answer, except to note that when two or three objects keep turning up together, there's probably a missing intermediate concept where some of the behaviour really belongs. The trick, when turning that concept into a type, is to give it a meaningful name so that it's hard to add features that don't belong.