2.8. 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.


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 MCU, 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 more like "Turn on the Battery Low LED" might be a lot more useful.

A block of comments before a section of code and at the beginning of the program 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. Even 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.8.2. Symbols

Use SYMBOL to 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:

Symbol	BattLED = Pin0	‘Assign Pin0 a more useful name
Symbol	Capacity = B1	‘Variable B1 will contain the remaining battery capacity

		If Capacity < 10 Then battlow	‘If battery capacity is low, go indicate it
		Goto othercode			‘Else go do something else

battlow:	BattLED = 1		‘Turn on the Battery Low LED
		Goto othercode		‘Go about other business

2.8.3. Labels

Labels should also be more meaningful than "label1:" or "here:". Even a label like "loop:" 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.8.4. GOTO

Finally, try not to use too many GOTOs. While the language is not as robust as it might be and GOTOs are 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.