Lesson 4
Effective Commenting and Documentation in Go
Introduction

Hello and welcome to this lesson on comments and documentation. In our previous lessons, we concentrated on the value of using meaningful names and crafting well-organized functions to enhance the readability and maintainability of clean code. In this session, we'll shift our focus to mastering the art of writing effective comments and documentation in Go, which act as guiding lights through complex sections of the code.

Commenting Practices at a Glance

Comments are a vital instrument for clarity, but they must be wielded judiciously. Below are scenarios where comments are truly beneficial:

  • Legal Comments: ✅ Use these to specify legal obligations and protect intellectual property.
  • Clarification: ✅ Aid understanding by explaining complex or non-obvious code logic.
  • Warning of Consequences: ✅ Highlight potentially risky operations to prevent unintended effects.
  • TODO Comments: ✅ Track tasks or improvements that need to be addressed in the future.
  • Go Documentation Comments: ✅ Use Go's documentation comments for exporting package-level identifiers, crucial for package usability and developer guidance.

Here are situations where comments can be detrimental:

  • Redundant Comments: 🔴 Eliminate comments that merely reiterate code.
  • Noise Comments: 🔴 Avoid comments that offer no meaningful insight.
  • Commented-Out Code: 🔴 Remove old code unless retaining it is justified with a reason.
Legal Comments

Legal comments are key to ensuring proper acknowledgment and protection of intellectual property. They're used to specify licensing or copyright information, offering legal clarity to users and contributors about the code's usage terms. This practice not only fosters trust but also shields against potential legal disputes:

Go
1/* 2 * Copyright 2023, XYZ Corporation. 3 * Licensed under the Apache License, Version 2.0. 4 */

These comments ensure that users and contributors are aware of the legal rights and restrictions associated with the code.

Clarification

Use comments to unravel complex logic in the code. It's not about stating the obvious but about offering insights where the code might be difficult to follow. This guidance can be invaluable for future developers or even your future self if you return to the code months or years later:

Go
1// Calculating square root using Newton's method for better precision 2sqrtValue := computeSquareRoot(value)

This comment clarifies the method's use and is helpful for future reference or updates.

Warning of Consequences

These comments serve as cautionary notes, alerting developers to potential impacts or risks within code execution. By highlighting operations that could lead to unintended side effects, they act as safeguards against misuse or oversight, especially in complex systems:

Go
1// Warning: This operation will overwrite existing data 2saveDataToDatabase(newData)

Such comments can prevent unintentional behavior that might occur from using certain operations.

TODO Comments

Mark sections with tasks or improvements that need attention. They're placeholders for future work, ensuring that ideas for enhancement or optimization don't get lost. Properly maintained TODO comments can help prioritize development focus and facilitate better project management:

Go
1// TODO: Add unit tests for edge cases 2func processInput() { 3 // Implementation 4}
Go Documentation Comments

Go's documentation comments provide essential information about package-level identifiers and exported elements. They serve as important notes for other developers looking to understand or use the package, detailing how to interact with the code:

Go
1// CalculateVolume returns the volume of a cylinder with the provided radius and height. 2func CalculateVolume(radius, height float64) float64 { 3 return 3.14159 * radius * radius * height 4}

These comments facilitate understanding how to properly use functions by describing parameters and return values in a straightforward manner.

Redundant Comments

Avoid comments that simply repeat what the code does. Redundant comments can clutter codebases, making code maintenance burdensome and distracting developers from meaningful insights. Strive to write code that is self-explanatory, so that each comment adds genuine value:

Go
1count := len(items) // 🔴 Sets count to the size of items

Here, the comment is unnecessary as the code is self-explanatory.

Noise Comments

Eliminate comments that don't add any meaningful insight. Noise comments serve no educational purpose and detract from the clarity of the code. Instead, they introduce more text for developers to parse, slowing down the comprehension process unnecessarily:

Go
1// 🔴 Now we increment i 2i++ 3// 🔴 End of increment

Noise comments obstruct the flow and make reading code cumbersome.

Commented-Out Code

Code that is commented out without explanation should be removed or clearly justified for being retained. Such remnants of old logic often confuse developers, who may not easily discern the reasoning for its storage. Always annotate with context if retaining code sections temporarily:

Go
1// var oldValue = computeOldValue(input) // Unused due to new algorithm

Preserving commented-out code should only happen when necessary, with a reason provided.

Summary

In this lesson, we explored various types of comments and documentation, emphasizing writing meaningful, succinct, and maintainable comments while avoiding redundant or noisy ones. You've also seen how to use Go's documentation comments effectively for public APIs and exported identifiers. As you proceed to the practice exercises, these guidelines will aid in honing your skills to create clean and well-documented code. Enjoy your practice and keep building those clean coding habits!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.