Documenting code

Properly commenting your code goes a long way toward understandability.

You are getting the first edition of all these pages. Please let me know if you find an error!

Motivation

Comments in code provide a way for you to leave notes to yourself and others about what your code does. These are very useful, if not essential, in a team setting. The term code documentation in general refers to the set of comments in source code that, hopefully, explain something about that code.

Code documentation is a double-edged sword. Done well, it helps you and others understand your code. Done poorly, it provides no value and can even mislead. Further, code documentation needs to be updated when the code is updated!

Three simple rules

We want our code documentation to be clear and concise, just like the code itself. Here is what we will focus on documenting.

  1. Code should be self-documenting to the greatest extent possible.
  2. Document the purpose of classes and modules (files).
  3. Document the purpose, parameters, return values, and exceptions of functions.

You can apply these rules to almost any language you encounter, and you will find that the recommendations for creating class and function comments different per language.

Self-documenting code

Self-documenting code is a popular term for “I can look at the code and understand it’s purpose.” How do you achieve that?

Naming

Use descriptive variable, function, and class names according to your team’s coding conventions.

Variables and classes should be nouns that describe the data.

  • Keep them short and concise, say, 16 characters max. Shorter is better.
  • Use plural nouns to represent lists, sets, and other collections.
  • Do not use built-in names for variables, like max, min, sum.
  • Examples:
    • for name in birds: where birds is a list of strings.
    • total = sum(scores)

Functions should be verbs or start with a verb. They should describe what the function does.

  • Again, strive to be concise.
  • If a phrase better describes the function, split the words with underscores (Python convention), such as compute_average_score(). In Java, you would use camelCase

Comments

In-line comments are useful but should not be abused. Use in-line comments to:

  1. Summarize a complex block of code.
  2. Explain an implementation or design choice.

Do not write a comment for every line. A programming proficient in the programming language should be able to understand your code if you use good variable names and your logic is clear. In cases where the logic is unclear or convoluted, a code comment is warranted to explain your implementation.

Docstrings

In Python, we document modules (.py files), classes, and functions with docstrings. Docstrings are part of the Python language syntax.

Some tools look for these docstring content in a particular content These tools can give you pop-up information about a module, class, or function:

An intellisense popup

Installing autoDocstring

We will install a Visual Studio Code extension to make writing docstrings simpler.

Go to the Extensions pane on the left side Extensions icon or press Ctrl+Shift+X.

Search for autoDocstring and install the extension by Nils Werner.

The store page for the autoDocstring extension

Creating docstrings for a module/file

On the first line of the file, put something similar to the following:

"""This module contains functions useful for counting birds."""

That’s it. You can add multi-line docstrings where needed like so:

1
2
3
4
5
"""
This module contains functions to load a bird osbervation file and count it.

It is used by the ornithologist package to load data for further processing.
"""

Place your cursor on the first line of the file (for modules), just below the class name, or just below the function name. then type """ and hit Enter. autoDocstring will create a template for you.

Creating docstrings for a class

Place a blank line below the class name line and type """. autoDocstring will prepare a template for you.

1
2
3
4
5
6
class Patient:
    """_summary_
    """

    def __init__(self, name, age, weight, height):
        # More code here

Simply replace the word _summary_ with whatever you want to say. Be concise and state the purpose of the class. Use multiple lines if desired.

Creating docstrings for a function

Place a blank line below the function name and type """. autoDocstring will prepare a template for you.

    def __init__(self, name, age, weight, height):
        """_summary_

        Args:
            name (_type_): _description_
            age (_type_): _description_
            weight (_type_): _description_
            height (_type_): _description_
        """
        self.name = name
        self.age = age
        self.weight = weight
        self.height = height

autoDocstring will create a _summary_ area to explain the purpose of the function. It will have an Args region for you to describe the types and purpose of each argument. It will also create an Exceptions region if your function explicitly raises exceptions.

Fill in the contents like so.

    def __init__(self, name, age, weight, height):
        """Constructor for the Patient class

        Args:
            name (_str_): first and last name
            age (_int_): age in years
            weight (_int_): weight in pounds
            height (_int_): height in inches
        """
        self.name = name
        self.age = age
        self.weight = weight
        self.height = height

Now with your docstrings set up, you will see helpful pop-ups in your IDE when you type class and function names!

Knowledge check

  • When are the two cases where an in-line comment is appropriate?
  • In Python, why is sum a bad variable name?
  • Why is doc() a bad function name?
  • For which three Python program elements do you write docstrings?
  • What are the four possible elements of a function docstring?
  • Does the docstring go inside or above the program element?
Last modified October 3, 2024.