The Art of Agile Development: Pair Programming

The second edition is now available! The Art of Agile Development has been completely revised and updated with all new material. Visit the Second Edition page for more information, or buy it on Amazon.

in 99 words

It's more fun than it sounds: two programmers at one computer. One drives; the other navigates. Switching roles fluidly, they constantly communicate. Together, they accomplish better work more quickly than either could alone.

The driver types. She focuses on tactics--writing clean code that compiles and runs. The navigator focuses on strategy--how the code fits into the overall design, which tests will drive the code forward, and which refactorings will improve the entire codebase.

Pairs self-organize by selecting partners who can best help with the current task. They switch every few hours to share perspectives and knowledge.

as haiku

Summer bakes the earth
Heads together, we ponder
Aha! An insight.

Behind the Scenes

Iterative Writing

Poster

'Pairing Tips' poster

Full Text

The following text is excerpted from The Art of Agile Development by James Shore and Shane Warden, published by O'Reilly. Copyright © 2008 the authors. All rights reserved.

Pair Programming

We help each other succeed.

Audience
Programmers
Whole Team

Do you want somebody to watch over your shoulder all day? Do you want to waste half of your time sitting in sullen silence watching somebody else code?

Of course not. Nobody does—especially not people who pair program.

Pair programming is one of the first things people notice about XP. Two people work at the same keyboard? It's weird. It's also extremely powerful and, once you get used to it, tons of fun. Most programmers I know who tried pairing for a month find that they prefer it to programming alone.

Why Pair?

This chapter is called Thinking, yet I included pair programming as the first practice. That's because pair programming is all about increasing your brainpower.

When you pair, one person codes—the driver. The other person is the navigator, whose job is to think. As navigator, sometimes you think about what the driver is typing. (Don't rush to point out missing semicolons, though. That's annoying.) Sometimes you think about what tasks to work on next and sometimes you think about how your work best fits into the overall design.

This arrangement leaves the driver free to work on the tactical challenges of creating rigorous, syntactically correct code without worrying about the big picture, and it gives the navigator the opportunity to consider strategic issues without being distracted by the details of coding. Together, the driver and navigator create higher-quality work more quickly than either could produce on their own.1

1One study found that pairing takes about 15% more effort than one individual working alone, but produces results more quickly and with 15% fewer defects [Cockburn & Williams]. Every team is different, so take these results with a grain of salt.

Pairing also reinforces good programming habits. XP's reliance on continuous testing and design refinement takes a lot of self-discipline. When pairing, you'll have positive peer pressure to perform these difficult but crucial tasks. You'll spread coding knowledge and tips throughout the team.

You'll also spend more time in flow—that highly-productive state in which you're totally focused on the code. It's a different kind of flow than normal because you're working with a partner, but it's far more resilient to interruptions. To start with, you'll discover that your office mates are far less likely to interrupt you when you're working with someone. When they do, one person will handle the interruption while the other continues his train of thought. Further, you'll find yourself paying more attention to the conversation with your programming partner than surrounding noise; it fades into the background.

If that isn't enough, pairing really is a lot of fun. The added brainpower will help you get past roadblocks more easily. For the most part, you'll be collaborating with smart, like-minded people. Plus, if your wrists get sore from typing, you can hand off the keyboard to your partner and continue to be productive.

How to Pair

I recommend pair programming on all production code. Many teams who pair frequently, but not exclusively, discover that they find more defects in solo code. A good rule of thumb is to pair on anything that you need to maintain, which includes tests and the build script.

When you start working on a task, ask another programmer to work with you. If another programmer asks for help, make yourself available. Never assign partners: pairs are fluid, forming naturally and shifting throughout the day. Over time, pair with everyone on the team. This will help improve team cohesion and it will spread design skills and knowledge throughout the team.

Get a fresh perspective by switching partners.

When you need a fresh perspective, switch partners. I usually switch when I'm feeling frustrated or stuck. Have one person stay on the task to help bring the new partner up to speed. Often, even explaining the problem to someone new will help you resolve it.

It's a good idea to switch partners several times per day even if you don't feel stuck. This will help keep everyone informed and moving quickly. I switch whenever I finish a task. If I'm working on a big task, I switch within four hours.

When you sit down to pair together, make sure that you're physically comfortable. Position your chairs side by side, allowing for each others' need for personal space, and make sure the monitor is clearly visible. When you're driving, place the keyboard directly in front of you. Keep an eye out for this one—for some reason, people pairing tend to contort themselves to reach the keyboard and mouse rather than moving them closer.

Ally
Test-Driven Development

Paired programmers produce code through conversation. As you drive or navigate, think out loud. Take small, frequent design steps—test-driven development works best—and talk about your assumptions, short-term goals, general direction, and any relevant history of the feature or project. If you're confused about something, ask questions. The discussion may enlighten your partner as much as it does you.

When a pair goes dark—talks less, lowers their voices, or doesn't switch off with other pairs—it's often a sign of technical difficulty.

Ally
Energized Work

Expect to feel tired at the end of the day. Pairs typically feel that they have worked harder and accomplished more than when working alone. Practice energized work to maintain your ability to pair every day.

Driving and Navigating

Pairing will feel natural in time.

When you start pairing, expect to feel clumsy and fumble-fingered as you drive. You may feel that your navigator sees ideas and problems much more quickly than you do. She does—navigators have more time to think than drivers do. The situation will reverse when you navigate. Pairing will feel natural in time.

When navigating, expect to feel like you want to step in and take the keyboard away from your partner. Relax; your driver will often communicate an idea with both words and code. He'll make typos and little mistakes—give him time to correct them himself. Use your extra brainpower to think about the greater picture. What other tests do you need to write? How does this code fit into the rest of the system? Is there duplication you need to remove? Can the code be more clear? Can the overall design be better?

As navigator, help your driver be more productive. Think about what's going to happen next and be prepared with suggestions. When I'm navigating, I like to keep an index card in front of me. Rather than interrupting the driver when I think of an issue, I write my ideas on the index card and wait for a break in the action to bring them up. At the end of the pairing session, I tear up the card and throw it away.

Ally
Spike Solutions

Similarly, when a question arises, take a moment to look up the answer while the driver continues to work. Some teams keep spare laptops on hand for this purpose. If you need more than a few minutes, research the solution together. Sometimes the best way to do so is to split up, pursue parallel lines of inquiry, and frequently come back together to share what you have learned. Spike solutions are a particularly powerful approach.

As you pair, switch roles frequently—at least every half hour, and possibly every few minutes. If you're navigating and find yourself telling the driver which keys to press, ask for the keyboard. If you're driving and need a break, pass the keyboard off to your navigator.

Pairing Stations

To enjoy pair programming, good pairing stations are essential. You need plenty of room for both people to sit side by side. Typical cubicles, with a workstation located in a corner, won't work. They're uncomfortable and require one person to sit behind another, adding psychological as well as physical barriers to peer collaboration.

You don't need fancy furniture to make a good pairing station; the best ones I've seen are just simple folding tables found at any good office supply store. They should be six feet long, so that two people can sit comfortably side-by-side, and at least four feet deep. Each table needs a high-powered development workstation. I like to plug in two keyboards and mice so each person can have a set.

Splurge on large monitors so that both people can see clearly. Some teams mirror the display onto two monitors, which makes things a little easier to see, but you may find yourself pointing to the wrong monitor. Others prefer to spread one desktop across two monitors.

For ideas about where to put the pairing stations, see "Sit Together" in Chapter 6.

Challenges

Pairing can be uncomfortable at first, as it may require you to collaborate more than you're used to. These feelings are natural and typically go away after a month or two, but you have to face some challenges.

Comfort

It bears repeating: pairing is no fun if you're uncomfortable. When you sit down to pair, adjust your position and equipment so you can sit comfortably. Clear debris off the desk and make sure there's room for your legs, feet, and knees.

Some people (like me) need a lot of personal space. Others like to get up close and personal. When you start to pair, discuss your personal space needs and ask about your partner's.

Similarly, while it goes without saying that personal hygiene is critical, remember that strong flavors such as coffee, garlic, onions, and spicy foods can lead to foul breath. Decide as a team, before any issues come up, how to notify people of challenging personal habits respectfully.

Mismatched Skills

Pairing is a collaboration between peers, but sometimes a senior developer will pair with a junior developer. Rather than treating these occasions as student/teacher situations, restore the peer balance by creating opportunities for both participants to learn. For example, if you know you'll be pairing with a junior developer, you could ask him to research a topic that no one else knows, such as the inner workings of a library that the team depends on. Give everyone a chance to be an expert.

Communication Style

Ally
Test-Driven Development

New drivers sometimes have difficulty involving their partners; they can take over the keyboard and shut down communication. To practice communicating and switching roles while pairing, consider ping-pong pairing. In this exercise, one person writes a test. The other person makes it pass and writes a new test. Then the first person makes it pass and repeats the process by writing another test.

The flip side of too little communication is too much communication—or rather, too much blunt communication. Frank criticism of code and design is valuable, but it may be difficult to appreciate at first. Different people have different thresholds, so pay attention to how your partner receives your comments. Try transforming declarations (such as "This method is too long") into questions or suggestions ("Could we make this method shorter?" or "Should we extract this code block into a new method?"). Adopt an attitude of collaborative problem solving.

Tools and Keybindings

Ally
Coding Standards

Even if you don't fall victim to the endless vi versus emacs editor war, you may find your coworkers' tool preferences annoying. Try to standardize on a particular toolset. Some teams even create a standard image and check it into version control. When you discuss coding standards, discuss these issues as well.

Questions

Isn't it wasteful to have two people do the work of one?

In pair programming, two people aren't really doing the work of one. Although only one keyboard is in use, there's more to programming than that. As Ward Cunningham said, "If you don't think carefully, you might think that programming is just typing statements in a programming language."2 In pair programming, one person is programming and the other is thinking ahead, anticipating problems, and strategizing.

2http://en.wikiquote.org/wiki/Ward_Cunningham, accessed 12 December 2006.

If you're looking for hard data, [Williams] has a chapter on pairing research. Keep in mind that the number of variables in software development make it notoriously difficult to conduct large-scale controlled studies. Sometimes the best way to know whether something will work for your team is just to try it.

How can I convince my team or organization to try pair programming?

Ask permission to try it as an experiment. Set aside a month in which everyone pairs on all production code. Be sure to keep going for the entire month, as pair programming may be difficult and uncomfortable for the first few weeks.

Don't just ask permission of management; be sure your fellow team members are interested in trying pairing as well. The only programmers I know who tried pairing for a month and didn't like it are the ones who were forced to do it against their will.

Do we really have to pair program all the time?

This is a decision that your whole team should make together. Before you decide, try pairing on all production code (everything you need to maintain) for a month. You may enjoy it more than you expect.

Regardless of your rule, you will still produce code that you don't need to maintain. (Spike solutions are one example.) These may benefit from individual study.

If you're bored while pairing, consider how you can make your design less repetitive.
Ally
Simple Design

Some production tasks are so repetitive that they don't require the extra brainpower a pair provides. Before abandoning pairing, however, consider why your design requires so much repetition. It could be an indication of a design flaw. Use the navigator's extra time to think about design improvements and consider discussing it with your whole team.

How can I concentrate with someone talking to me?

When you navigate, you shouldn't have too much trouble staying several steps ahead of your driver. If you do, ask your driver to think out loud so you can understand her thought process.

As driver, though, you may sometimes find that you're having trouble concentrating. Let your navigator know—she may have a suggestion that will help you get through the roadblock. At other times, you may just need a few moments of silence to think through the problem.

If you have trouble concentrating, try taking smaller steps.
Ally
Test-Driven Development

If you find yourself in this situation a lot, you may be taking steps that are too large. Use test-driven development and take very small steps. Rely on your navigator to keep track of what you still need to do (tell her if you have an idea; she'll write it down) and focus only on the few lines of code needed to make the next test pass.

Ally
Spike Solutions

If you are working with a technology you don't completely understand, consider taking a few minutes to work on a spike solution. You and your partner can work on this together or separately.

What if we have an odd number of programmers?

Ally
Exploratory Testing

A programmer flying solo can do productive tasks that don't involve production code. She can research new technologies, or learn more about a technology the team is using. She can pair with a customer or tester to review recent changes, polish the application, or do exploratory testing. She could be the team's batman (see "Iteration Planning" in Chapter 8).

Alternatively, a solo programmer may wish to spend some time reviewing the overall design—either to improve his own understanding, or to come up with ideas for improving problem areas. If a large refactoring is partially complete, the team may wish to authorize a conscientious programmer to finish those refactorings.

If your team is on the smaller side, you may run out of useful solo tasks. In this case, consider relaxing the "no production code" rule or bringing in another programmer.

There are only two (or three) of us. Should we still pair all the time?

Even a saint will get on your nerves if you have to pair with him day-in, day-out. Use your own judgment about when to pair and when you need time to yourself. If you feel fine but your pair is getting cranky, don't escalate; just say you're tired and need a break.

I pair-programmed with the same person for three months straight during a two-person project. I think it helped that we had a large office and a big desk: it gave us room to move around. We also kept a mini-fridge stocked with goodies.

Even with these comforts, I had my cranky moments. Perhaps the most important factor was that my partner was a very laid-back, easy-going person who put up with my occasional bad mood.

We get engrossed in our work and forget to switch pairs. How can we encourage more frequent pair switching?

One approach is to remember that you can switch when you feel stuck or frustrated. In fact, this is a perfect time to switch partners and get a fresh perspective.

Some teams use kitchen timers to switch partners at strictly defined intervals. [Belshee] reports interesting results from switching every ninety minutes. While this could be a great way to get in the habit of switching pairs, make sure everybody is willing to try it.

How can we pair remotely?

You can use a phone headset and a desktop sharing tool such as VNC or NetMeeting to pair remotely. I have heard of teams who use individual workstations with shared screen sessions and VoIP applications.

When I tried this, I found it to be a poor substitute for pairing in person. XP teams usually sit together, so remote pairing isn't often necessary.

Results

When you pair program well, you find yourself focusing intently on the code and your work with your partner. You experience fewer interruptions and distractions. When interrupted, one person deals with the problem while the other continues thinking. Afterward, you slide back into the flow of work immediately. At the end of the day, you feel tired yet satisfied. You enjoy the intense focus and the camraderie of working with your teammates.

The team as a whole enjoys higher quality code. Technical debt decreases. Knowledge travels quickly through the team, raising everyone's level of competence and helping to integrate new team members quickly.

Contraindications

Pairing requires a comfortable work environment (see "Sit Together" in Chapter 6 for design options). Most offices and cubicles just aren't set up that way. If your workspace doesn't allow programmers to sit side-by-side comfortably, either change the workspace or don't pair program.

Similarly, if your team doesn't sit together, pairing may not work for you. Although you can pair remotely, it's not as good as in-person.

Programmer resistance may be another reason to avoid pairing. Pairing is a big change to programmers' work styles and you may encounter resistance. I usually work around this by asking people to try it for a month or two before making a final decision. If they still resist, you're probably better off avoiding pairing rather than forcing anyone to pair against their will.

Alternatives

Pairing is a very powerful tool. It reduces defects, improves design quality, shares knowledge amongst team members, supports self-discipline, and reduces distractions; all without sacrificing productivity. If you cannot pair program, you need alternatives.

Formal code inspections can reduce defects, improve quality, and support self-discipline. However, my experience is that programmers have trouble including inspections in their schedules, even when they're in favor of them. Pairing is easier to do consistently, and it provides feedback much more quickly than scheduled inspections. If you're going to use inspections in place of pairing, add some sort of support mechanism to help them take place.

Inspections alone are unlikely to share knowledge as thoroughly as collective code ownership requires. If you cannot pair program, consider avoiding collective ownership, at least at first.

If you'd still like to have collective code ownership, you need an alternative mechanism for sharing knowledge about the state of the codebase. I've formed regular study groups in which programmers meet daily for a timeboxed half-hour to review and discuss the design.

Ally
Energized Work

I'm not aware of any other tool that helps reduce distractions as well as pair programming does. However, I find that I succumb to more frequent distractions when I'm tired. In the absence of pairing, put more emphasis on energized work.

Further Reading

Pair Programming Illuminated [Williams] discusses pair programming in depth.

"The Costs and Benefits of Pair Programming" [Cockburn & Williams] reports on Laurie Williams' initial study of pair programming.

"Promiscuous Pairing and Beginner's Mind: Embrace Inexperience" [Belshee] is an intriguing look at the benefits of switching pairs at strict intervals.

"Adventures in Promiscuous Pairing: Seeking Beginner's Mind" [Lacey] explores the costs and challenges of promiscuous pairing. It's a must-read if you plan to try Belshee's approach.

Peer Reviews in Software: A Practical Guide [Wiegers] discusses formal inspections and peer reviews.

If you liked this entry, check out my best writing and presentations, and consider subscribing to updates by email or RSS.