11.07.2015 Views

tYSR20

tYSR20

tYSR20

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 29: Ten Ways to Avoid Adding Bugs to Your Program 379Adopting a Clear and ConsistentCoding StyleCoding in a clear and consistent style not only enhances the readability ofthe program but also results in fewer coding mistakes. Remember, the lessbrain power you have to spend deciphering C++ syntax, the more you haveleft over for thinking about the logic of the program at hand. A good codingstyle 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, #definedobjects should stand out) Identify blocks of C++ code at the same level (this is the result of consistentindentation)In addition, you need to establish a standard module header that providesinformation about the functions or classes in the module, the author (presumably,that’s you), the date, the version of the compiler you’re using, anda 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 isconfusing.Limiting the VisibilityLimiting the visibility of class internals to the outside world is a cornerstoneof 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 accessibleoutside the class — that is, they should be marked as protected. (Thereis another storage class, private, that is not discussed in this book.) In addition,member functions that the application software does not need to knowabout should also be marked protected. Don’t expose any more of the classinternals than necessary.A related rule is that public member functions should trust application codeas little as possible. Any argument passed to a public member functionshould 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:

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!