2.2 Coding

Coding is an art, and XP acknowledges that. Your success at XP depends largely on your love of coding. Without good code, the exponential cost of change as shown in Figure 2-1 is inevitable. Let's look at some specific ways that XP helps keep code simple.

One of the most frustrating misconceptions about XP is that it is a chaotic approach to software development that caters to hackers. The opposite is true. XP works best with meticulous, detail-oriented programmers who take great pride in their code.

2.2.1 Simplicity

Just getting code to work is not good enough, because the first solution you come up with is hardly ever the simplest possible solution. Your methods may be too long, which makes them harder to test. You may have duplicated functionality, or you may have tightly coupled classes. Complex code is hard to understand and hard to modify, because every little change may break something else in the system. As a system grows, complexity can become overwhelming to the point where your only remaining option is to start over.

When compared to beginners, expert programmers typically implement superior solutions using fewer lines of code. This is a hint that simplicity is harder than complexity, and takes time to master.

Simple code is self-documenting because you pick meaningful names, your methods are concise, and your classes have clearly defined responsibilities. Simple code is hard to achieve, and relies on knowledge in the areas of object-oriented programming, design patterns, and other facets of software engineering.

2.2.2 Comments

If code is self-documenting, do you need source code comments? In short, there will always be cases where you need comments, but you should never write comments simply for the sake of commenting. If the meaning of a method is completely obvious, you do not need a comment. An abundance of comments in code is often an indication that the code is unclear and in need of refactoring. Let's look at a method that needs a comment, and see how to eliminate this need.

/**
 * Sets the value of x.
 * @param x the horizontal position in pixels.
 */
public void setX(int x) {
    this.x = x;
}

This method needs a comment because the meaning of "x" is not entirely clear. Over time, the comment might not be kept in sync if someone changes the method's implementation or signature. But what if we rename things to make the code more clear? How about this:

public void setXPixelPosition(int xPixelPosition) {
    this.xPixelPosition = xPixelPosition;
}

This code no longer needs a comment because it is self-documenting. As a result, we end up typing a little bit more for the method declaration, but save a few lines of comments. This helps us out in the long run because we don't have to spend time and effort keeping the comment in sync with the code. Long method names do not degrade performance in any appreciable way, and are easy to use thanks to code-completion features found in any modern IDE.

2.2.3 Pair Programming

As mentioned earlier, XP teams work in pairs. These pairs of programmers share a single computer, keyboard, and mouse. Having dual monitors is a good idea because both programmers can then see the screen clearly, although this is not a requirement. Desks should be configured so that two people can sit side-by-side comfortably, and the entire team should work in the same room.

Here is how pair programming works:

  1. You pick out a user story[3] for your next task.

    [3] A user story is a requirement from the customer. Stories are typically written on index cards, and the customer decides which stories are the most important.

  2. You ask for help from another programmer.

  3. The two of you work together on a small piece of functionality.

    • Try to work on small tasks that take a few hours.

    • After the immediate task is complete, pick a different partner or offer to help someone else.

By working on small tasks, partners rotate frequently. This method facilitates communication between team members and spreads knowledge. As mentioned earlier, writing simple code is hard, and experienced programmers are generally better at it. By pairing people together, beginners can gain valuable coding experience from the experts.

Pair programming is critical because XP requires a very high degree of discipline in order to be successful. As we will learn in the next section, programmers must write unit tests for each new feature added to the application. Writing tests takes a great deal of patience and self-discipline, so having a partner often keeps you honest. When you start to get lazy about writing tests, it is the partner's job to grab the keyboard and take over.

When you have control of the keyboard, you are thinking about the code at a very fine-grained level of detail. When you are not the partner doing the typing, you have time to think about the problem at a higher level of abstraction. The observer should look for ways to simplify the code, and think about additional unit tests. Your job is to help your partner think through problems and ultimately write better code.

2.2.4 Collective Code Ownership

XP teams do not practice individual code ownership. Every team member is able to work on any piece of code in the application, depending upon the current task. The ability to work on any piece of code in an application makes sense when pairs of programmers are constantly shuffling and re-pairing throughout the day. Over time, most of the programmers see and work on code throughout the application.

Collective code ownership works because you can always ask someone else for help when you work on unfamiliar classes. It also works because you have a safety net of unit tests. If you make a change that breaks something, a unit test should catch the error before you and your partner integrate the change into the build. The tests also serve as great documentation when you are working with unfamiliar code.

Collective ownership facilitates communication among team members, avoiding situations where the entire team depends on the one person who understands the custom table sorting and filtering framework. The shared ownership model also encourages higher quality, because programmers know that other team members will soon be looking at their code and potentially making changes.

2.2.5 Coding Standards

Collective code ownership and pair programming ensure that all team members are constantly looking at each other's code. This is problematic when some programmers follow radically different coding conventions. Your team should agree on a consistent set of coding conventions in order to minimize the learning curve when looking at each other's code.

Picking coding conventions can turn into a bitter argument, as programmers become very attached to their personal style. It's ironic, because code style has absolutely no bearing on the functionality of the compiled application.

Consider using a code-formatting tool that automatically formats code according to your team standards.

If everyone on your team is agreeable, coding standards might be a non-issue. Otherwise, either try to hammer out an agreement or select an industry standard set of conventions such as the JavaSoft coding guidelines.[4] You might be able to win people over by adopting standards written by a neutral party.

[4] The examples in this book follow JavaSoft coding guidelines, available at http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html/.

2.2.6 Code Inspections

Code inspections are a great technique for validating the quality of code. In typical projects, programmers work in isolation for several weeks, and then present their code to a group of peers for a formal inspection meeting. People often talk about how great code inspections are, but procrastinate until the last minute. At this point, it is generally too late to inspect everything and it might be too late to make changes if you find problems.

Code inspections are a valuable tool, so why not inspect code constantly? XP teams do not rely on formal code inspections, primarily because all of the code is constantly reviewed as it is developed by pairs of programmers. As programmers migrate to new partners and work on different parts of the system, code is constantly enhanced and refactored by people other than the original author.