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

Chapter 29

Ten Ways to Avoid Adding Bugs to Your Program

In This Chapter

Enabling all warnings and error messages

Insisting on clean compiles

Using a clear and consistent coding style

Limiting the visibility

Adding comments to your code while you write it

Single-stepping every path at least once

Avoiding overloaded operators

Heap handling

Using exceptions to handle errors

Avoiding multiple inheritance

In this chapter, I look at several ways to minimize errors, as well as ways to make debugging the errors that are introduced easier.

Enabling All Warnings

and Error Messages

The syntax of C++ allows for a lot of error checking. When the compiler encounters a construct that it cannot decipher, it has no choice but to gener­ ate an error message. Although the compiler attempts to sync back up with the next statement, it does not attempt to generate an executable program.

378 Part VI: The Part of Tens

Disabling warning and error messages is a bit like unplugging the Check Engine light on your car dashboard because it bothers you: Ignoring the problem doesn’t make it go away. If your compiler has a Syntax Check from Hell mode, enable it. Both Visual Studio.NET and Dev-C++ have an Enable All Messages option — set it. You save time in the end.

During all its digging around in your source code, a good C++ compiler also looks for suspicious-looking syntactical constructs, such as the following code snippet:

#include “student.h” #include “MyClass.h”

Student* addNewStudent(MyClass myObject, char *pName, SSNumber ss)

{

Student* pS;

if (pName != 0)

{

pS = new Student(pName, ss); myObject.addStudent(pS);

}

return pS;

}

Here you see that the function first creates a new Student object that it then adds to the MyClass object provided. (Presumably addStudent() is a member function of MyClass.)

If a name is provided (that is, pName is not 0), a new Student object is created and added to the class. With that done, the function returns the Student cre­ ated to the caller. The problem is that if pName is 0, pS is never initialized to anything. A good C++ compiler can detect this path and generate a warning that “pS might not be initialized when it’s returned to the caller and maybe you should look into the problem,” or words to that effect.

Insisting on Clean Compiles

Don’t start debugging your code until you remove or at least understand all the warnings generated during compilation. Enabling all the warning mes­ sages if you then ignore them does you no good. If you don’t understand the warning, look it up. What you don’t know will hurt you.

Chapter 29: Ten Ways to Avoid Adding Bugs to Your Program 379

Adopting a Clear and Consistent

Coding Style

Coding in a clear and consistent style not only enhances the readability of the program but also results in fewer coding mistakes. Remember, the less brain power you have to spend deciphering C++ syntax, the more you have left over for thinking about the logic of the program at hand. A good coding style enables you to do the following with ease:

Differentiate class names, object names, and function names

Know something about the object based on its name

Differentiate preprocessor symbols from C++ symbols (that is, #defined objects should stand out)

Identify blocks of C++ code at the same level (this is the result of consis­ tent indentation)

In addition, you need to establish a standard module header that provides information about the functions or classes in the module, the author (pre­ sumably, that’s you), the date, the version of the compiler you’re using, and a modification history.

Finally, all programmers involved in a single project should use the same style. Trying to decipher a program with a patchwork of different coding styles is confusing.

Limiting the Visibility

Limiting the visibility of class internals to the outside world is a cornerstone of object-oriented programming. The class is responsible for its own internals; the application is responsible for using the class to solve the problem at hand.

Specifically, limited visibility means that data members should not be acces­ sible outside the class — that is, they should be marked as protected. (There is another storage class, private, that is not discussed in this book.) In addi­ tion, member functions that the application software does not need to know about should also be marked protected. Don’t expose any more of the class internals than necessary.

A related rule is that public member functions should trust application code as little as possible. Any argument passed to a public member function should be treated as though it might cause bugs until it has been proven safe. A function such as the following is an accident waiting to happen:

380 Part VI: The Part of Tens

class Array

{

public: Array(int s)

{

size = 0;

pData = new int[s]; if (pData)

{

size = s;

}

}

~Array()

{

delete pData; size = 0; pData = 0;

}

//either return or set the array data int data(int index)

{

return pData[index];

}

int data(int index, int newValue)

{

int oldValue = pData[index]; pData[index] = newValue; return oldValue;

}

protected: int size; int *pData;

};

The function data(int) allows the application software to read data out of Array. This function is too trusting; it assumes that the index provided is within the data range. What if the index is not? The function data(int, int) is even worse because it overwrites an unknown location.

What’s needed is a check to make sure that the index is in range. In the fol­ lowing, only the data(int) function is shown for brevity:

int data(unsigned int index)

{

if (index >= size)

{

throw Exception(“Array index out of range”);

}

return pData[index];

}

Chapter 29: Ten Ways to Avoid Adding Bugs to Your Program 381

Now an out-of-range index will be caught by the check. (Making index unsigned precludes the necessity of adding a check for negative index values.)

Commenting Your Code

While You Write It

You can avoid errors if you comment your code as you write it rather than waiting until everything works and then go back and add comments. I can understand not taking the time to write voluminous headers and function descriptions until later, but you always have time to add short comments while writing the code.

Short comments should be enlightening. If they’re not, they aren’t worth much. You need all the enlightenment you can get while you’re trying to make your program work. When you look at a piece of code you wrote a few days ago, comments that are short, descriptive, and to the point can make a dra­ matic contribution to helping you figure out exactly what it was you were trying to do.

In addition, consistent code indentation and naming conventions make the code easier to understand. It’s all very nice when the code is easy to read after you’re finished with it, but it’s just as important that the code be easy to read while you’re writing it. That’s when you need the help.

Single-Stepping Every

Path at Least Once

It may seem like an obvious statement, but I’ll say it anyway: As a program­ mer, it’s important for you to understand what your program is doing. Nothing gives you a better feel for what’s going on under the hood than single-stepping the program with a good debugger. (The debugger in both Dev-C++ and Visual Studio.NET work just fine.)

Beyond that, as you write a program, you sometimes need raw material in order to figure out some bizarre behavior. Nothing gives you that material better than single-stepping new functions as they come into service.

Finally, when a function is finished and ready to be added to the program, every logical path needs to be traveled at least once. Bugs are much easier to