Documenting and commenting the code

Reading time5 min

In brief

Article summary

In this article, we provide details on code documentation, and the role it plays in software development, especially whan writing cdes aimed to be released.

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.

Article contents

1 — What does it mean to document a code?

1.1 — Why documenting?

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.

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.

1.2 — Various sorts of documentations

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 (end-user documentation) – 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.

2 — Code documentation

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.

2.1 — 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.

Information

There is a balance to find between not enough comments (thus leading to hard to read code) and too many comments (thus leading to hard to read code). Depending on the context (e.g., education, team work), this balance may be adjusted.

In Python, comments begin with the character # (// in Java). This symbol indicates that the rest of the line is a comment. Comments can be written on several lines (in Java, a multi-line comment can be surrounded by /* and */).

def inverse_capitalization (word: str) -> str:

    # Fill a list char by char
    result = []
    for char in word: # Loop over the characters of the word <-- Not very useful comment
        result.append(char.lower() if char.isupper() else char.upper()) # In Python we can make if conditions like this
    
    # Recreate the string
    return ''.join(result)
public String inverseCapitalization(String word){
    // Fill an array char by char
    char[] result = new char[word.length()];
    for (int i = 0; i < word.length(); i++) {
        char c = word.charAt(i);
        result[i] = Character.isUpperCase(c) ? Character.toLowerCase(c) : Character.toUpperCase(c); // In Java we can make if conditions like this
    }

    // Recreate the string
    return new String(result);
}

2.2 — 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 raised, 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:

    """
        Inverts the capitalization of a word.
        For instance Hello should be transformed to hELLO.
        In:
            * word: The word to process.
        Out:
            * The word with inversed capitalization.
    """

    # Fill a list char by char
    result = []
    for char in word:
        result.append(char.lower() if char.isupper() else char.upper())
    
    # Recreate the string
    return ''.join(result)
/**
 * Inverts the capitalization of a word.
 * For instance Hello should be transformed to hELLO.
 *
 * @param word The word to process.
 * @return     The word with inversed capitalization.
 */
public String inverseCapitalization(String word){
    // Fill an array char by char
    char[] result = new char[word.length()];
    for (int i = 0; i < word.length(); i++) {
        char c = word.charAt(i);
        result[i] = Character.isUpperCase(c) ? Character.toLowerCase(c) : Character.toUpperCase(c); // In Java we can make if conditions like this
    }

    // Recreate the string
    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.

To go further

Looks like this section is empty!

Anything you would have liked to see here? Let us know on the Discord server! Maybe we can add it quickly. Otherwise, it will help us improve the course for next year!

To go beyond