Why Use Comments and Documentation?



Comments and documentation help us to explain parts of the code that don't look obvious at first sight. While the goal of clean code is to make the code itself self-explanatory, sometimes adding a bit of explanation can save time for other developers or even yourself later on. Comments clarify the why behind a piece of code, not just the how.

Types of Comments

Different kinds of comments serve different purposes. Heres a breakdown of the main types youll come across or use:

  • Inline Comments: These comments go on the same line as the code theyre explaining. Theyre usually brief and explain what a particular line does. But dont overuse them; only add inline comments when the code is doing something tricky or non-obvious.
 let totalAmount = calculateTotal(); // Total after discounts
  • Block Comments: Block comments use multiple lines and are often used to describe a more complex section of code. Youll usually find them at the start of a function or method explaining what it does.
  •  
    /*
     * This function calculates the total amount by summing
     * the item prices in the cart and then applying discounts.
     */
    function calculateTotal(cartItems) {
     // ...
    }
    
  • Doc Comments (Documentation Comments): These comments provide a description of methods, classes, or even entire modules. They are used in documentation tools that generate formal documentation from code. Its helpful to use these when youre working on a project that will be used or maintained by others.
  •  
    /**
     * Calculates the total amount to be paid.
     * @param {Array} cartItems - The items in the cart.
     * @returns {number} The total amount.
     */
    function calculateTotal(cartItems) {
     // ...
    }
    

    When to Use Comments?

    • To Explain Why, Not What: If the code does something that isnt obvious from the implementation, explain why its necessary. Avoid stating what the code does, as it should already be clear from the code itself.

      // Need to check if the user is authenticated here to avoid
      // unauthorized access to sensitive data.
      if (!user.isAuthenticated()) {
       throw new Error('Unauthorized');
      }
      
    • Document Complex Logic: If theres an algorithm or process that's really complex and not easy to understand by other developers or beginners, you can add a comment to explain the reasoning behind that particular approach. It can help someone understand the logic faster.

       // This loop uses binary search to find the target value in the sorted array.
      // Binary search is more efficient than a linear search in this case.
      while (low <= high) {
       // ...
      }
      

    When NOT to Use Comments?

    Avoid Obvious Comments: If a comment is just stating what the code already tells you, it's redundant. Don't add comments like:

    let userAge = 25; // Set user age to 25
    

    The code is self-explanatory; the comment doesnt add value.

    Don't Comment Out Code: If you don't need a certain code and you need to remove it, just delete it. Don't just comment it out. Commenting out old code increases complexity and makes it hard to follow and understand. You can use version control systems like Git to track changes instead of commenting on everything unnecessary.

    • Keep It Updated: If you change how a function works, update its comments and documentation. Outdated comments are worse than no comments because they can mislead developers and this can cause disaster.
    • Be Concise: Keep comments to the point. Explain only what's necessary without adding too much detail.
    • Use Proper Formatting: When writing documentation comments, follow consistent formatting rules to make them easier to read and parse by documentation tools.

    Commenting Standards

    Use TODO Comments for Incomplete Work: When you know something is missing or needs improvement, add a TO comment. Its like a little reminder for later.

    
    // TODO: Add error handling for network failures
    

    Use FIXME for Known Issues: If there's a problem that needs to be fixed, mark it with FIX so it stands out.

    // FIXME: This calculation fails when the input is negative
    

    Comment Style

    • Keep Comments Consistent: Use the same style throughout the codebase. If your comments are formatted in a certain way at one place, try to keep it that way everywhere in your codebase.
    • Use Clear Language: Even if your code is technical, keep the comments simple and easy to understand. Don't use jargon, abbreviations, or complex words that only you might know.
    • Write Comments in English: Use a common language that helps everyone working on the code to understand the comments, especially in international teams. Using common language makes collaboration better.

    Example of Clean Code with Comments

    /**
     * Fetches user data from the server and updates the UI.
     * @param {string} userId - The ID of the user.
     */
    async function fetchUserData(userId) {
       try {
          let userData = await getUserFromServer(userId);
          updateUserInterface(userData);
       }catch (error) {
          // Log the error and show a user-friendly message.
         console.error(error);
          alert('Failed to fetch user data. Please try again later.');
       }
    }
    // This variable tracks the current session status.
    let sessionActive = true;
    

    Conclusion

    Comments and documentation aren't used to only writing down everything. Theyre there to clarify, explain intentions, and help others understand the code's context. Use comments wisely and carefully, focus only on explaining "why" rather than "what," and keep them up-to-date and consistent throughout your code.

    Advertisements