DEV Community

Discussion on: To comment or not to comment?

Collapse
 
appeltel profile image
Eric Appelt

I write docstrings.

I learned to use docstrings in python and naturally use them because I work mostly in python currently. But if I reverted back to C++ or another language that has no built in support for docstrings, I would still try to write "comments" formatted like a docstring. A docstring is a bit of definitive and explanatory text that accompanies the declaration of a function or other object. Quoting python standard PEP-257:

The docstring for a function or method should summarize its behavior and document its arguments, return value(s), side effects, exceptions raised, and restrictions on when it can be called (all if applicable). Optional arguments should be indicated. It should be documented whether keyword arguments are part of the interface.

The docstring for a class should summarize its behavior and list the public methods and instance variables. If the class is intended to be subclassed, and has an additional interface for subclasses, this interface should be listed separately (in the docstring). The class constructor should be documented in the docstring for its init method. Individual methods should be documented by their own docstring.

Every "public" class, function, or method gets a docstring that conforms to the above.

I've heard in many places that the name and call signature of a function should be self-explanatory of how to use it, and the code should be self explanatory as to what it does. But if you think about it, this is an extremely tall order in most cases, especially when code is written under a deadline.

One of the major benefits of factoring code out into small functions (ideally without side-effects) is that the developer doesn't have to handle the cognitive load of what all of the application code does all at once. So even if code can be reasonably described as being self-explanatory, in the absence of docstrings or comments the developer still has to read and understand how the function does what it does when all they really needed was to know what it does. This is a distraction from the developer's task at hand - writing the calling function and understanding it's internal state.

Additionally, following a common format for docstrings on all functions opens the door to automating the generation of API documentation. This is particularly useful as it is much easier to ensure that documentation of the API is up to date when it is right in front of you whenever making a change to a function or method.

As far as actual non-docstring comments, I rarely write any and they usually describe the why behind something that came up in some subtle edge case, just to make sure any further modification takes note of the special problem, i.e. "# We need to detach foo before linking quux in cases of network congestion, see ticket 38745".