Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Professional C++ [eng].pdf
Скачиваний:
284
Добавлен:
16.08.2013
Размер:
11.09 Mб
Скачать

Chapter 7

avoiding symbols such as * and &. They’re also easy to use, so you should have no problem adopting references into your style palette.

Another benefit of references is that they clarify ownership of memory. If you are writing a method and another programmer passes you a reference to an object, it is clear that you can read and modify the object, but you have no easy way of freeing its memory. If you are passed a pointer, this is less clear. Do you need to delete the object to clean up memory? Or will the caller do that? Your group should determine how variable passing techniques imply memory ownership. One simple way is to agree that, if your code is given a pointer, it owns the memory and should do any necessary cleanup. All other variables are passed as references or copies.

The function prototype that follows makes it clear that the parameter will be changed, but, because it is a reference, the memory will not be freed.

void changeMe(ChessBoard& outBoard);

Use Custom Exceptions

C++ makes it easy to ignore exceptions. Nothing about the language syntax forces you to deal with exceptions, and you could easily write error-tolerant programs with traditional mechanisms such as returning NULL or setting an error flag.

Exceptions provide a much richer mechanism for error handling, and custom exceptions allow you to tailor this mechanism to your needs. For example, a custom exception type for a Web browser could include fields that specify the Web page that contained the error, the network state when the error occurred, and additional context information.

Chapter 15 contains a wealth of information about exceptions in C++.

Language features exist to help the programmer. Understand and make use of features that contribute to good programming style.

Formatting

Many programming groups have been torn apart and friendships ruined over code-formatting arguments. In college, one of the authors got into such a heated debate with a peer over the use of spaces in an if statement that people were stopping by to make sure that everything was okay.

If your organization has standards in place for code formatting, consider yourself lucky. You may not like the standards they have in place, but at least you won’t have to argue about it. If everybody on your team is writing code their own way, try to be as tolerant as you can. As you’ll see, some practices are just a matter of taste, while others actually make it difficult to work in teams.

152

Coding with Style

The Curly Brace Alignment Debate

Perhaps the most frequently argued-about point is where to put the curly braces that demark a block of code. There are several styles of curly brace use. In this book, we put the curly brace on the same line as the leading statement, except in the case of a function, class, or method name. This style is shown in the code that follows (and throughout the book).

void someFunction()

{

if (condition()) {

cout << “condition was true” << endl;

} else {

cout << “condition was false” << endl;

}

}

This style conserves vertical space while still showing blocks of code by their indentation. Some programmers would argue that preservation of vertical space isn’t relevant in real-world coding (especially if you’re getting paid by the line of code!) A more verbose style is shown below.

void someFunction()

{

if (condition())

{

cout << “condition was true” << endl;

}

else

{

cout << “condition was false” << endl;

}

}

Some programmers are even liberal with use of horizontal space, yielding code like that in the following example.

void someFunction()

{

if (condition())

{

cout << “condition was true” << endl;

}

else

{

cout << “condition was false” << endl;

}

}

Of course, we won’t recommend any particular style because we don’t want hate mail.

153

Chapter 7

When selecting a style for denoting blocks of code, the important consideration is how well you can see which block falls under which condition simply by looking at the code.

Coming to Blows over Spaces and Parentheses

The formatting of individual lines of code can also be a source of disagreement. Again, we won’t advocate a particular approach, but we will show you a few styles that you are likely to encounter.

In this book, we use a space after any keyword and use parentheses to clarify the order of operations, as follows:

if (i == 2) {

j = i + (k / m);

}

The alternative, shown next, treats if stylistically like a function, with no space between the keyword and the left parenthesis. Also, the parentheses used above to clarify the order of operations inside of the if statement are omitted because they have no semantic relevance.

if( i == 2 ) {

j = i + k / m;

}

The difference is subtle, and the determination of which is better is left to the reader, yet we can’t move on from the issue without pointing out that if is not a function!

Spaces and Tabs

The use of spaces and tabs is not merely a stylistic preference. If your group does not agree on a convention for spaces and tabs, there are going to be major problems when programmers work jointly. The most obvious problem occurs when Alice uses four spaces to indent code and Bob uses five space tabs; neither will be able to display code properly when working on the same file. An even worse problem arises when Bob reformats the code to use tabs at the same time that Alice edits the same code; many source code control systems won’t be able to merge in Alice’s changes.

Most, but not all, editors have configurable settings for spaces and tabs. Some environments even adapt to the formatting of the code as it is read in, or always save using spaces even if the tab key is used for authoring. If you have a flexible environment, you have a better chance of being able to work with other people’s code. Just remember that tabs and spaces are different because tabs can be any length and a space is always a space. For this reason, we recommend that you use an editor that always translates tabs into four spaces.

154