Ova

What is Internal Commentary?

Published in Code Documentation 5 mins read

Internal commentary refers to descriptive notes and explanations embedded directly within the source code of a program, designed to be read by developers rather than executed by the computer. These comments allow a programmer to add descriptions, notes, or explanations to their code that will not be translated when the program runs. Instead, they are entirely ignored by the compiler or interpreter, ensuring they have no impact on the program's execution, performance, or output. They serve as valuable documentation that can be read by anyone with access to the code, significantly enhancing clarity and maintainability.


Why is Internal Commentary Crucial?

Beyond simply clarifying code, internal commentary plays a vital role in the entire software development lifecycle. It acts as an embedded knowledge base for developers, both current and future.

  • Enhancing Code Readability: Complex algorithms or intricate logic can be challenging to decipher. Comments break down these complexities into understandable segments.
  • Facilitating Collaboration: In team environments, clear comments allow developers to quickly grasp the intent and functionality of code written by others, fostering smoother teamwork.
  • Simplifying Maintenance: As software evolves, code needs updates, bug fixes, and feature additions. Well-documented code makes these tasks much easier, reducing the time and effort required for maintenance.
  • Aiding Debugging and Troubleshooting: Comments can highlight potential areas of concern, known limitations, or specific conditions that need attention during debugging.
  • Explaining Design Choices: They provide context by documenting why certain architectural decisions were made, rather than just what the code does.

Common Forms of Internal Commentary

Internal commentary typically comes in two primary forms, each suited for different explanatory needs:

  1. Single-Line Comments:

    • Purpose: Used for brief explanations, short notes, or quickly commenting out a single line of code.
    • Placement: Usually appear on the same line as the code they describe or on the line directly above it.
    • Example (JavaScript):
      let count = 0; // Initialize the counter variable
  2. Multi-Line Comments (Block Comments):

    • Purpose: Ideal for more extensive descriptions, function documentation, copyright notices, or temporarily disabling larger blocks of code.
    • Placement: Can span multiple lines, often enclosing a paragraph of text.
    • Example (Java):
      /*
       * This function calculates the total price of items
       * in a shopping cart, applying any valid discounts.
       * It assumes prices are positive integers.
       */
      public double calculateTotalPrice(List<Item> items) {
          // ... function implementation
      }

How Different Languages Handle Comments

The specific syntax for internal commentary varies significantly across programming languages. Understanding these differences is essential for writing effective comments in any given language.

  • Python:
    • Single-line: Starts with # (e.g., # This is a comment).
    • Multi-line: Often uses triple quotes ("""...""" or '''...''') which, while technically string literals, are ignored if not assigned to a variable, thus commonly serving as docstrings or multi-line comments.
  • JavaScript, Java, C#, C++:
    • Single-line: Starts with // (e.g., // This is a comment).
    • Multi-line: Enclosed by /* ... */ (e.g., /* This is a multi-line comment */).
  • HTML:
    • Multi-line: Enclosed by <!-- ... --> (e.g., <!-- This part of the page is under construction -->). HTML does not have a dedicated single-line comment syntax.
  • CSS:
    • Multi-line: Enclosed by /* ... */ (e.g., /* Style for the main navigation bar */). CSS also lacks a dedicated single-line comment.

Table: Comment Syntax Examples by Language

Language Single-line Syntax Multi-line Syntax Common Use Cases
Python # line comment """docstring""" Code explanation, function/class documentation
JavaScript // line comment /* block comment */ Code explanation, debugging, temporary disabling
Java // line comment /* block comment */ /** Javadoc */ Code explanation, API documentation (Javadoc)
C++ / C# // line comment /* block comment */ Code explanation, debugging, compiler directives
HTML N/A <!-- block comment --> Hiding content, notes for web developers
CSS N/A /* block comment */ Explaining styles, organizing stylesheets

Best Practices for Effective Internal Commentary

While adding comments is beneficial, poor commenting can be as unhelpful as no comments at all. Adhering to best practices ensures your internal commentary genuinely adds value.

  • Focus on Why, Not What: Code should generally be self-explanatory regarding what it does. Comments should clarify why a particular approach was taken, how it solves a specific problem, or any non-obvious implications.
  • Keep Them Up-to-Date: Outdated or inaccurate comments are misleading and can cause more harm than good. Always update comments when the corresponding code changes.
  • Avoid Redundancy: Do not comment on obvious code. For example, i = i + 1; // Increment i is redundant.
  • Be Concise and Clear: Use plain language and get straight to the point. Avoid overly verbose or ambiguous explanations.
  • Explain Complex Logic: Use comments to break down intricate algorithms, complex regular expressions, or non-obvious design patterns into understandable parts.
  • Use TODOs and FIXMEs: Employ specific tags like TODO, FIXME, BUG, or HACK to mark areas needing future attention, refactoring, or known issues. This is particularly useful for project management and future development.
  • Maintain Consistency: Follow a consistent style for your comments across the entire codebase, ideally aligning with team or project guidelines (e.g., Google's Python Style Guide).

Example Scenario for Internal Commentary

Consider a function designed to calculate the final price after a discount:

def apply_discount(price, discount_percentage):
    # Validate the discount percentage to ensure it's within a reasonable range.
    # This prevents erroneous calculations and potential negative prices.
    if not 0 <= discount_percentage <= 100:
        raise ValueError("Discount percentage must be between 0 and 100.")

    # Calculate the actual discount amount based on the original price.
    discount_amount = price * (discount_percentage / 100)

    # Subtract the discount to determine the final price.
    final_price = price - discount_amount

    return final_price

"""
TODO: Implement tiered discounts for loyal customers.
BUG: Edge case: Large floating-point numbers might cause precision issues. Consider using Decimal.
"""

In this Python example:

  • The first comment clarifies the reason for the input validation (preventing errors).
  • Subsequent comments explain the purpose of each step in the calculation.
  • The final multi-line comment uses TODO and BUG tags to identify future tasks and potential issues, providing immediate context for developers revisiting the code.

By providing this internal commentary, the code becomes significantly more accessible and maintainable for anyone who reads it, including the original developer in the future.