The Art of Pair Programming

Pair programming (PP) is one of the eXtreme Programming (XP) practices. When doing pair programming, two programmers share a mouse and keyboard while they write code. One of the two, the driver, types, while the other, the navigator, reviews the code, and thinks ahead. The two persons switch roles often. This is another example of XP ‘turning the knobs to 10′: if reviewing code is good, then we should do it all the time.

There is a good post on PP by Rod Hilton. He starts out with

When I first heard I’d be pairing at the new job, I was a bit apprehensive and skeptical.

I can relate to that. At a former company I worked for, I introduced XP. I had just read XP Explained: Embrace Change and thought it could improve our software development process. But pair programming was the one practice I was apprehensive about. The thought of someone watching over your shoulder all day made me feel uneasy. Yet the book made it clear that PP is a foundational practice, so I tried to keep an open mind.

I shouldn’t have worried. Rod explains that PP has nothing to do with “looking over a shoulder”:

The way pair programming works in practice is quite a bit different than I imagined it. [...] When doing Test-Driven Development, one of the things we do is called “ping-pong pairing”. So the other developer will write a test, then make it compile but fail. Then he passes the keyboard to me. I implement the feature just enough to make the test pass, then I write another failing test and pass it back.

I didn’t know about ping-pong pairing when we started out doing XP. In fact, Rod’s post introduced it to me. It seems like a really good technique, and I’d love to try it out.

Also, the “all day” part is a misconception:

In reality, you don’t sit down at a desk with another person and work all day with them. You pair up for tasks. [...] When the task is done and code is checked in, the pair breaks up. Generally tasks only have 2 hour estimates (sometimes less) so you’re only pairing for the two hours. Then you pair up with someone else to work on another task. [...] We take breaks often because getting away from the code for a few minutes helps keep a fresh perspective when you come back to the task.

When I did XP, we paired up for about three hours at a time. We all came in on different times, so PP time generally started at about 9:30 AM, and lasted till lunch. Then we’d switch pairs. Since some of us started early, they also left early (Sustainable Pace), so there was another session of about three hours in the afternoon.

Pairing for about six hours a day is really enough. PP is pretty intense! There is no chance to let your mind wander off a bit, to look out of the window for more than a couple of seconds or to read e-mail. You have to stay focused all the time.

Advantages

So why bother at all with PP? Rod explains:

I see pairing work so well every day that I consider my career prior to my current job to have consisted mostly of wasting time. [...] When you have a second person working with you, you find that you try harder to code well. You’re far, far less likely to be willing to apply duct tape to a problem, because someone else is working with you and he or she is more likely to object to the duct tape.

We all know the feeling, I guess. You know that you’re taking a shortcut, that there is a better way. But that would take more effort. When you’re pairing, your partner “keeps you honest”. You don’t want to look like a slouch, so you don’t even consider the shortcut.

This makes a big difference. In fact, while I consider myself a pretty good programmer, I must admit that the code I wrote when pairing was of considerable higher quality than the code written solo. And that is true even when pairing with someone that I knew for sure was a lesser programmer than me!

The “keeping you honest” thingie is one reason for this. “Two brains think of more than one” is another. The interplay between the driver and navigator is a subtle one. When you, as a driver, see the navigator’s eyes go blank, you know you’re code is not as clear as it could be. And you fix it. You either stop to explain, at which point the navigator will likely suggest an improvement (like a better name for a class to better express its purpose), or you switch roles and let the navigator write better code.

Disadvantages

So why isn’t everybody pairing? What’s the catch?

Well, there are downsides. Rod mentions one:

Hygiene can be a serious problem. If one person smells, it’s rough to sit with them. I find myself going back to my desk often and the code suffers for it. If you’re pairing, take a shower, and hold your farts for your next bathroom trip. Just do it, you filthy pig.

I haven’t dealt with this problem much. One guy I paired with was a smoker, so whenever he came back from a smoke outside, I’d smell the smoke. I didn’t like it, but so what. We all have our faults. Pair programming is a partnership, and like in any partnership, you need to give and take a bit ;) PP takes some time to get good at, but the basics skills should have been acquired at Kindergarten.

Rod also mentions productivity:

there’s no denying that you’re producing fewer lines of code per day since only half your team is coding at any one point. I don’t consider that a bad thing, though (if you have two solutions that equally solve a problem, the solution with fewer lines of code is the superior one) because the QUALITY of the code that IS produced is so, so, so much higher.

This is an important point to stress. Pair programming seems wasteful, but it’s really not. The limiting factor when programming is not the speed with which you type, but the number of bugs you don’t introduce. There hasn’t been much scientific research into this, but there is one nice experiment by Alistair Cockburn and Laurie Williams that finds that PP takes 15% more time, but produces 15% less bugs, while yielding a significantly simpler design. My experiences confirm this.

The long term benefits of these advantages cannot be overestimated. Each bug takes away future coding time, since it needs to be fixed. And more complex designs slow you down as well, because it requires more time to understand the code you’re working on, and increases the chances of introducing bugs because of misunderstandings.

Of course, there will always be nay-sayers. Most of them haven’t actually tried PP, because “that could never work”. Well, if you don’t want to learn, then don’t, but don’t bother me. If you did give PP a try and failed to get good results, I must press you to check whether you did PP properly. If you think you did and still didn’t like PP, then please leave a comment explaining why.

Unit testing a user interface

So I’m on this new cool Google Web Toolkit (GWT) project of ours now. Part of the UI consists of a series of HTML labels that is the view to our model. Since our model has a tree structure, we use the visitor pattern to create this UI.

This all works beautifully, except when it doesn’t, i.e. when there is a bug. With all the recursion and the sometimes convoluted HTML that is required to achieve the desired effect, hunting down bugs isn’t always easy.

So it was about time to write some unit tests. Normally, I write the tests first. But I was added to this project, and there weren’t any tests yet. So I decided to introduce them. Now, it is often easier to start with tests than add them later. If you don’t start out by writing tests, you usually end up with code that is not easily testable. That was also the case here.

Making the code testable

So my first job was to make sure the code became testable. I started out by separating the creation of the HTML labels from the visitor code, since I didn’t want my tests to depend on GWT. So I introduced a simple TextStream:

public interface TextStream {
  void add(String text);
}

The visitor code is injected with this text stream and calls the add() method with some HTML markup. Normally, this TextStream is a HtmlLabelStream:

public class HtmlLabelStream implements TextStream {

  private final FlowPanel parent;

  public HtmlLabelStream(final FlowPanel parent) {
    this.parent = parent;
  }

  public void add(final String text) {
    parent.add(new HTML(text));
  }

}

But my test case also implements the TextStream interface, and it injects itself into the visitor. That way, it can collect the output from the visitor and compare it with the expected output.

Simplifying testing

Now I got a whole lot of HTML code that I needed to compare to the desired output. It was hard to find the deviations in this, since the required HTML is rather verbose.

So I decided to invest some time in transforming the incoming HTML into something more readable. For instance, to indent some piece of text, the HTML code contains something like this:

<div style="padding-left: 20px">...</div>

For each indentation level, 10px were used. So I decided to strip the div, and replace it with the number of spaces that corresponds to the indentation level. I repeated the same trick for a couple of other styles. In the end, the output became much easier to read, and thus much easier to spot errors in. In fact, it now looks remarkably similar to what is rendered by the browser.

This certainly cost me time to build. But it also won me time when comparing the actual and expected outputs. And adding a new test is now a breeze. Which is just the sort of incentive I need for my fellow team mates to also start writing tests…