Comments
Programs are instructions to computers.
But programs are written by humans, and so need to be understood by humans. Why? Hard-to-understand programs are harder to fix (if they have a bug), and harder to extend (if the program's task changes). So, it is important to keep programs easily understood by humans.
One aid to comprehension is using comments. In Smojo, we have two kinds of comments:
- Stack comments are only used in Word definitions, to document the before/after state of the stack by that Word.
- Line comments can be used anywhere in your program, either to better document its behaviour or explain tricky sections of code, or to document possible problems or points for future extensions.
(starts a Stack comment, and discards anything up to and including the closing parenthesis ). Similarly, Line comments are preceded by the word
\and discards everything up to the end of the line.
Stack Comments
Consider this program:
: double ( n -- n ) dup +. ; 2.5 double .Clearly,
DOUBLEsimply doubles the top of the stack: It consumes one item on top of the stack and puts back one item. So, the appropriate stack comment is
( n -- n ).
- "n" represents any number.
- Sometimes, we want to be specific about the number, so common practice is to use "i" for integers and "d" for reals (d for Double, a synonym for real).
- Similarly, "f" is used to indicate a boolean (true/false) ( f = flag ).
- Items in double-quotes mean text. Eg: "text"
(is a word, so you need to put spaces before and after it.
Line Comments
There are no rules for using Line comments, you use them anywhere you like to document your code. Some guidelines:
- Keep line comments brief but to the point. They should not overwhelm the code.
- Do use line comments to describe the proper usage of a word, especially if it is not obvious.
- Line comment anything that is not obvious to "competent" programmers. Certainly, comment anything that is not obvious to you.
- It is bad practice to comment the obvious. Don't do it, because it makes your code harder to read.
- Don't be tempted to follow mindless rules like "x comments per y lines of code". Leave the mindless rule following to computers!
Quiz
Question 1
Why are stack comments useful? Do they have any drawbacks?
Stack comments can specify the pre-condition and post-condition of the stack, but they do not specify the behaviour of the words.
Question 2
How would you stack comment the following code:
: add3 + + ;Does you stack comment help humans understand how
ADD3works?
: add3 ( i i i -- i ) + + ;By reading the stack comment, one can know that
add3expects 3 numbers as input and produces 1 number as output.