4.7. Defensive Coding

The best way to avoid program errors is to write perfect code. Since that's not going to happen anytime soon (I've been waiting for over 30 years), the next best thing is to write your code with the expectation that something may go wrong. The first step in this defensive strategy is simple:

Write your code so someone else can easily understand it.

Consider the following list of things you can do in your program source code to make it easier to understand.

4.7.1. Use Program Comments

A program comment is simply a message you leave in the program to help the reader understand the code. There is an art to using comments. Too few comments force the reader to take more time to understand what the program is doing. Too many comments can actually get in the way of the code by adding unnecessary clutter. Commenting every line in a program is almost never necessary. At the other extreme, I've seen instances where the code is so complex that it was easier to put in the name and page numbers of a book than to explain it ourselves. Try to use comments for those statement(s) that do something unusual or are critical to processing the data. Simply stated, a comment should make it easier for the reader to understand your code, and not get in the way of that understanding.

There are two types of program comments: single-line comments and multi-line comments. Always keep in mind that comments are ignored by the compiler, so they have no impact on the performance of the ...

Get Beginning C# 3.0 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.