08. Comments and notes to yourself — Homework solutions
The .go solution files are in
exercises/08/homework/solutions/.
Problem 1 — Annotate a program
Problem. Add a header and two why comments without changing the output.
How to think about it. Comments never affect output, so this is pure communication. The header says what the file does; inline comments explain choices a reader might wonder about.
Worked solution.
// Prints a tiny scoreboard line for one player.
// Used to check the score formula by eye.
package main
import "fmt"
func main() {
fmt.Println("Player: Keiko") // the scoreboard only tracks one player for now
// Everyone starts the round with 50. The 25 is the reward for a no-damage run.
fmt.Println("Score:", 50+25)
}Output, the same as before:
Player: Keiko
Score: 75
Common mistakes.
// add 50 and 25over the print line just repeats it. Explain why 25 is the bonus, not that it is added.
Problem 2 — Find the bug by commenting out
Problem. Switch off one line so the output is
start then end.
Worked solution.
package main
import "fmt"
func main() {
fmt.Println("start")
// fmt.Println("this line should not be here")
fmt.Println("end")
}Common mistakes.
- Deleting the line instead of commenting it. Commenting keeps it in case you want it back.
Problem 3 — Switch off a block
Problem. Use one /* */ block to switch
off the three middle lines.
Worked solution.
package main
import "fmt"
func main() {
fmt.Println("first")
/*
fmt.Println("middle 1")
fmt.Println("middle 2")
fmt.Println("middle 3")
*/
fmt.Println("last")
}Output:
first
last
Common mistakes.
- Forgetting the closing
*/. Go does not quietly switch off the rest of the file; it stops withcomment not terminatedand runs nothing.
Challenge — Why, not what
Problem. Replace repeat-the-code comments with useful ones.
How to think about it. For each line, ask "would a reader already know this from the code?" If yes, the comment is noise — cut it or give the reason instead.
Worked solution. Before:
package main
import "fmt"
func main() {
fmt.Println("Lives:", 3) // print 3 lives
fmt.Println("Lives:", 3-1) // print 3 minus 1 lives
}After:
package main
import "fmt"
func main() {
fmt.Println("Lives:", 3) // standard start; three tries per game
fmt.Println("Lives:", 3-1) // player walked into the lava
}Common mistakes.
- Rewording every comment instead of cutting. Sometimes the best comment is none — if the code is clear, silence is fine.
Done?
You can now leave notes that help instead of clutter, and switch code on and off without deleting it. Next is The print toolkit, deeper into showing things on screen.