Documenting And Commenting Your Code

Reading time5 min

Important takeaways

Documentation and tests together ensure the long-term robustness and sustainability of the software.

  • Documenting code makes it easier to read and maintain, facilitating teamwork and knowledge sharing.
  • New developers can get up to speed more quickly with well-documented code.
  • Good documentation helps in debugging by explaining code logic and supports thorough testing by outlining expected behaviors and edge cases.

Introduction

Code documentation plays a crucial role in making the project readable and understandable for all developers. It includes comments within the code, usage guides, and detailed descriptions of functions and classes. Well-written documentation allows other developers, or even your future self, to quickly grasp the functionality and architecture of the software, reducing the time needed to get up to speed with the project. Additionally, comprehensive documentation fosters better collaboration among team members, as it provides a shared understanding of the codebase and its intended behavior. This is particularly valuable in large or distributed teams where clear communication is essential. Moreover, it aids in debugging and testing by clearly outlining the expected inputs, outputs, and edge cases, thus minimizing errors and enhancing the overall quality of the software. In summary, thorough documentation is an investment that pays off by improving efficiency, collaboration, and code quality in any development project.

Documenting your code

Documented code is crucial for several reasons. Firstly, it enhances the readability and maintainability of the software. When code is well-documented, other developers can easily understand its purpose, structure, and functionality without having to decipher the logic on their own. This is particularly important in a team setting or for new developers joining a project, as it significantly reduces the onboarding time. Additionally, documentation provides valuable context about why certain decisions were made, which is essential for future maintenance and refactoring. Without proper documentation, the risk of introducing errors during updates or modifications increases, as the intent behind the original code may be misunderstood.

It acts as a reference guide, detailing the usage of functions, classes, and modules, which helps in ensuring consistency and correctness throughout the development process. Good documentation also supports better collaboration, as team members can rely on the documented code to understand how different parts of the system interact. Moreover, it facilitates the integration of new features and debugging, as developers can trace the documented logic to identify potential issues more efficiently.

Well-documented code is essential for maintaining high quality, scalable, and collaborative software development practices. Here are some common types of documentation in software development:

  • Code Documentation: This type of documentation is embedded directly within the source code and includes comments, annotations, and docstrings. It explains the purpose, functionality, and usage of individual code elements such as functions, classes, and modules. Code documentation helps developers understand and maintain the codebase efficiently.

  • Technical Documentation: Technical documentation provides detailed information about the software’s architecture, design, and implementation. It may include system architecture diagrams, data flow diagrams, class diagrams, and other technical specifications. Technical documentation is primarily intended for developers, architects, and technical stakeholders to understand the inner workings of the software.

  • User Documentation: also known as end-user documentation, is aimed at helping users understand how to use the software effectively. It includes user manuals, guides, tutorials, and FAQs that provide instructions, tips, and troubleshooting advice. User documentation helps users learn how to interact with the software and accomplish their tasks efficiently.

Here, we focus on code documentation. In that context, there are two main types of documentation used to explain different aspects of the code: comments and documentation of function and class signatures.

Comments

Comments are textual annotations added directly to the source code. The purpose of the comments is to make the code easier to understand, not to paraphrase it. They explain how it works, its intentions, or provide additional information about complex or non-trivial parts of the code. They can be used to describe algorithms, design decisions, limitations, TODOs, etc.

In Python, comments begin with the character # (// in Java), it indicates that the rest of the line is a comment. Comments can be written on several lines.

def inverse_capitalization(word: str) -> str:
    result = [] # temporary array to store the result
    # Loop over the characters of the word <-- USELESS COMMENT !
    for char in word:
        # if c is uppercase, store its lowercase version 
        # otherwise store its uppercase version
        result.append(char.lower() if char.isupper() else char.upper())
    return ''.join(result)
public String inverseCapitalization(String word){
    char[] result = new char[word.length()]; // temporary array to store the result
    // Loop over the characters of the word <-- USELESS COMMENT !
    for (int i = 0; i < word.length(); i++) {
        // if c is uppercase, store its lowercase version 
        // otherwise store its uppercase version
        char c = word.charAt(i);
        result[i] = Character.isUpperCase(c) ? Character.toLowerCase(c) : Character.toUpperCase(c);
    }
    return new String(result);
}

Note that in Java, a multi-line comment can be surrounded by /* and */.

Documentation of function and class signatures

In many programming languages, it is possible to provide documentation of the signature of functions and classes. This documentation describes input parameters, return values, exceptions thrown, etc. This information can be extracted automatically to generate external documentation.

Python supports documentation strings, often called “docstrings”, which begin and end with """. These are multi-line comments included directly in the source code. Docstrings are usually placed just after the declaration of a function, method or class. They can be used to provide documentation embedded directly in the code.

In Java, these comments begin with /** and end with */ and are generally placed just before the declaration of a function, method or class.

Here is an example of a documented function:

def inverse_capitalization(word: str) -> str:
    """
    Inverse the capitalization of a word.
    It consists in iterating over the characters of the word
    and for each character, inverting its capitalization.
    That is, if a letter is uppercase, it will be transformed to lowercase and vice-versa.
    :param word: a word to inverse the capitalization
    :return: the word with the capitalization inversed 
    """
    result = [] # temporary array to store the result
    for char in word:
        # if c is uppercase, store its lowercase version 
        # otherwise store its uppercase version
        result.append(char.lower() if char.isupper() else char.upper())
    return ''.join(result)
/**
 * Inverse the capitalization of a word.
 * It consists in iterating over the characters of the word
 * and for each character, inverting its capitalization.
 * That is, if a letter is uppercase, it will be transformed to lowercase and vice-versa.
 *
 * @param word a word, as a String
 * @return a new String, with the capitalization inverted
 */
public String inverseCapitalization(String word){
    char[] result = new char[word.length()]; // temporary array to store the result
    for (int i = 0; i < word.length(); i++) {
        // if c is uppercase, store its lowercase version 
        // otherwise store its uppercase version
        char c = word.charAt(i);
        result[i] = Character.isUpperCase(c) ? Character.toLowerCase(c) : Character.toUpperCase(c);
    }
    return new String(result);
}

Documentation comments are the best way to generate automatic documentation from source code. They create detailed external documentation for classes and methods, which developers can consult when using these components.