Avoiding Errors with Good Comments - dummies

Avoiding Errors with Good Comments

By Jim Sizemore, John Paul Mueller

A lot of people dismiss comments as an exercise designed to waste time. But comments are actually invaluable in helping you to remember why you did something in a certain way and to avoid techniques that haven’t worked in the past. Beyond general documentation, however, comments can help you avoid mistakes.

Following are some of the benefits that you derive from good comments:

  • Comments can document techniques that have or haven’t worked in the past.

  • You can use comments as a means for telling someone the purpose of a script, function, or method — reducing the potential for using the wrong code for a particular need.

  • A good comment tells why something is done in a certain manner, which helps ensure that code changes don’t introduce errors.

  • Full commenting means documenting inputs and outputs so that everyone knows how to interact with a script, function, or method.

  • Knowing whom to contact about a particular issue is a first line of defense against errors because the originator can usually tell someone how to avoid problems.

  • Documenting the environment in which code is designed to operate helps you understand when errors are caused by updates to other software (and not the script, function, or method itself).

The best policy is to avoid errors whenever you can. Avoiding an error is always less costly than recovering from an error. However, the most costly error of all is one that is fatal and causes the application to crash. When applications crash, people lose data and organizations lose customers. Proper documentation helps people to understand your code better and avoid mistakes before they happen (or even before someone can think of a way to make the error in the first place).

The best comment in the world can’t prevent all errors. Some errors simply happen, and there is nothing you can do about them. For example, you can’t avoid an error that occurs as the result of a lightning strike (data errors introduced by electrical current induced into a network connection). Sometimes hardware glitches and third-party software that MATLAB uses to perform tasks can contain errors, too. Many sources of errors are outside your control, but using comments effectively helps you reduce the number of errors that you can control.