Comment or Not

We (developers) read code way more often than we write it, whether it’s someone’s else code or our own code written a while ago. Sometimes code is simple enough that It reads as plain English, but sometimes we can spend hours re-reading and debugging while trying to comprehend what is going on. So how easy and hard to read code is different?
Well, algorithmic complexity matters, the harder algorithm is, the harder is to comprehend code that implements it. Also being honest, code quality may be far away from ideal. However, a clear and precise “message of wisdom” in form of a comment can help to improve code readability whether it’s complex or little messy code.

Should code be self-documenting?

It is fair to ask, “Why do I have to write comments? Should code be self-documenting?”

In general it is definite yes. The main idea is to make code easy and fast to read.  Best if code is self-documenting, however there are two cases when comments help to improve code readability and comprehension. The cases are:

  • A comment helps to revels intend behind the code.
  • A comment explains complex algorithm or data structure the code implements.

The goal is to figure out which of the above cases you are trying to address, may be a mix of both, and execute precisely on that. Try to provide enough information and all necessary hints to a future-reader, however maintain brevity. Lengthy comments take time to read.

More on each case below.

Revealing intend or “Why?”

Sometimes it is not clear why code is doing what it is doing. Reasons can be:

  • Complex or obscure business logic that code addresses.
  • Code represents a fix to a bug that requires certain context.
  • An exception from rules that similar code follows.
  • Code optimization that is not obvious.
  • Algorithm choice is not obvious, while alternatives seem to be better options.
  • Any other “Whaaat?” or “Huh?!” moment.

To address this case white a comment that answers question “Why?”.

Complex algorithm or “What?”

In general code should be written in a way that reveals what it is doing, hence comments become unnecessary. However, sometimes we have to implement a complex algorithm or a data structure that is hard to realize by just looking at the code. In such cases comments that answer question “What?” are extremely useful.

Do we have to explain the whole algorithm in comments?

The answer is “It depends.” If the algorithm is publicly known, it may be enough to state the algorithm name and share a link to the paper that describes it. Additionally, we may explain why the algorithm was chosen and what alternatives were considered. If you are inventing you own algorithm you can document it where your team usually keeps documentation and share the link in the comment.

How?

When thinking about whether to write a comment or how to formulate it there is simple mental exercise that can help. Imagine yourself reading the code half a year later and trying to make sense of it. Would a comment help you to understand the code faster? What would you include in the comment? Would you like to share any context related to the code? Is there any condition that was not implemented intentionally? Add anything else that would make the code intention clear.

Should I comment every line?

If comments are so useful, should I comment every single line?

Well, not really. Excessive comments (especially the one that replicate code one to one) unnecessary increase the amount of text a reader needs to go through, they duplicate already made statements, hence do not add any value. Therefore, avoid excessive and code-duplicating comments.

Examples of redundant comments.

// If seam is null, then throw exception
if (seam == null) {
    throw new IllegalArgumentException("seam can not be null.");
}

...

// Iterate over all points
for (int i = 0; i < points.length; i++) {
    ...
}

...

public TopologicalShortestHorizontalPath(double[][] energies) {
    // Assign values to energies, width and height
    this.energies = energies;
    this.width = this.energies.length;
    this.height = this.energies[0].length;
}

Documenting API

API documentation is usually done with code comments, however approach to writing API and public interfaces documentation is slightly different to the way we write inline comments. The main purpose of API documentation is to reveal behavior of API to its client (developer) without making the developer to read source code. Most of programming languages such as C#, Java, Python and other do have idiomatic or well recognized API documentation formats. I would strongly recommend to follow those. IDEs and code editors usually understand idiomatic documentation formats making it easy for developer to understand API. There are also tools like Doxygen that can generate textual or web documentation from you code that uses idiomatic or well-established API documentation format.

Example of Java standard documentation format.

/**
 * Energy of pixel at column x and row y.
 *
 * @param x column X.
 * @param y column Y.
 * @return Energy of pixel at column x and row y.
 */
public double energy(int x, int y) {
...
}

Does spelling matter?

Yes, it does matter. Spelling and grammar matter a lot. Erroneous spelling diverges reader’s attention and creates an urge to fix it. Poor grammar makes it hard to comprehend the message a comment delivers.

Etiquette

Be professional, use proper language and avoid calling names or blaming other people in comments. If one of your colleagues made a silly mistake or failed to write clean code, feel free to fix it, explain your fix with a comment (if it improves code readability) and call it a day.

Humor

Should I sprinkle my comment with little bit of humor?

While humor is usually perceived positively and is very welcome in many settings, comments is not one of these. Remember, the main objective of comments is to help reader comprehend code, while humor creates destruction and diverges attention.

Conclusion

Having comments in the code does not indicate poor design or lack of attention, so write comments where it adds value, makes code easier to read and comprehend, but be mindful and follow principles above. Your colleagues and future-self will appreciate the effort you put today in writing wise comments.

Posts created 20

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top