<<Previous

Next>>

2.6. Coding Style

Writing readable and maintainable programs is an art. There are a few simple techniques you can follow that may help you become an artist.

2.6.1. Comments

Use lots of comments. Even though it may be perfectly obvious to you what the code is doing as you write it, someone else looking at the program (or even yourself when you are someone else later in life) may not have any idea of what you were trying to achieve. While comments take up space in your BASIC source file, they do not take up any additional space in the PICmicro so use them freely.

Make the comments tell you something useful about what the program is doing. A comment like "Set Pin0 to 1" simply explains the syntax of the language but does nothing to tell you why you have the need to do this. Something like "Turn on the Battery Low LED" might be a lot more useful.

A block of comments at the beginning of the program and before each section of code can describe what is about to happen in more detail than just the space remaining after each statement. But don=t include a comment block instead of individual line comments - use both.

At the beginning of the program describe what the program is intended to do, who wrote it and when. It may also be useful to list revision information and dates. Specifying what each pin is connected to can be helpful in remembering what hardware this particular program is designed to run on. If it is intended to be run with a non-standard crystal or special compiler options, be sure to list those.

2.6.2. Pin and Variable Names

Make the name of a pin or variable something more coherent than Pin0 or B1. In addition to the liberal use of comments, descriptive pin and variable names can greatly enhance readability. The following code fragment demonstrates:

BattLED var PORTB.0		' Low battery LED
level	var	byte		' Variable will contain the battery level

	If level < 10 Then	' If batt level is low
		High BattLED	' Turn on the LED
	Endif

2.6.3. Labels

Labels should also be more meaningful than Alabel1:" or Ahere:@. Even a label like Aloop:@ is more descriptive (though only slightly). Usually the line or routine you are jumping to does something unique. Try and give at least a hint of its function with the label, and then follow up with a comment.

2.6.4. GOTO

Try not to use too many GOTOs. While GOTOs may be a necessary evil, try to minimize their use as much as possible. Try to write your code in logical sections and not jump around too much. GOSUBs can be helpful in achieving this.

<<Previous

Next>>