Writing Code for the Next Person
Commenting Code
One of the most important things one can do is to comment code. There are a few reasons, but let's start with this trivial code example that helps to make it clear why.
START ORCC #$50
PSHS X,D
LDX $10D
STX RETAD
LDX #INT
STD $10D
LDX #MSG
LOOP1 LDA ,X+
BEQ EXIT1
JSR [$A002]
BRA LOOP1
EXIT1 PULS D,X
ANDCC #$AF
RTS
RETAD FDB 0000
MSG FCC "This is the message to render"
FBC 0
This is perfectly good code. I suspect most developers can recognize that this is assembly code for some processor, but what does this do?
Maybe you might consider it unfair to expect anyone to know an old assembly language, but the reality is that not every programmer knows the syntax of every language, knows every processor, understands the purpose of a every function, object, module, or whatever.
Sometimes, all it takes is just a little documentation to make the purpose clear. Consider the following version.
START ORCC #$50 Disable interrupts
PSHS X,D Push registers onto the stack
LDX $10D Load the current interrupt address
STX RETAD Store it for later use
LDX #INT Load the address of our interrupt routine
STD $10D Direct interrupts to our routine
LDX #MSG Load the address of the message to display
LOOP1 LDA ,X+ Loop while rendering each character
BEQ EXIT1
JSR [$A002] Call ROM routine to render the character
BRA LOOP1
EXIT1 PULS D,X Pull registers off the stack
ANDCC #$AF Enable interrupts
RTS Return
RETAD FDB 0000 Place to store IRQ address
MSG FCC "This is the message to render"
FBC 0
There is more to the program, of course, most important being the interrupt handler this code inserts into the interrupt chain. In fact, that missing part is the bulk of the program. But, this snippet is sufficient to illustrate how useful comments can be.
Some might argue that this level of commenting is overkill. Sometimes
it is, but sometimes it's necessary. If one is familiar with this processor,
one would know what PSHS/PULS does, so documenting those lines may not be
so important. However, the ORCC line is non-obvious without the comment
for even many people who might know this particular processor's assembly
language. The JSR [$A002]
line is specific to a particular
computer, so it is even less obvious.
I have shown this example to colleagues in the past as a means of making it clear why commenting is important. Normally, they see the light once they see the comments beside otherwise undecipherable lines of code.
Commenting and documenting code is important for both sustainability and increased productivity, and this includes files descriptions, function descriptions, inline comments, and system documentation.