Step 17: Comment Only What the Code Cannot Say ~ Kevin Henney
This is the Seventeenth Step towards gaining the Programming Enlightenment series. If you didn’t learn the Sixteenth Step, read it.
“Real programmers don’t comment their code. If it was Hard to Write, it should be Hard to Understand”
~ Tom Van Vleck
“Good Code is self-documenting”. It’s a cliché.
We already read about how we should make our code self-documenting in Step 16. Here we try to discuss about when we should comment.
When you should comment?
Comments aren’t necessarily evil.
They are also necessary. Most modern languages have a tool like javadoc that parses formatted comments to automatically build an API document. These Documentation Comments are almost necessary as they will be read by people who consume your APIs. Such as the one below for String class in Java.
**
* The <code>String</code> class represents character strings. All
* string literals in Java programs, such as <code>"abc"</code>, are
* implemented as instances of this class.
* <p>
But, in cases where it’s relevant to put in Clarification comments we should add comments. In the below snippet from String.java class, it beautifully defines what those fields are relevant for in addition to what they already offer through their great naming.
/** Cache the hash code for the string */
private int hash; // Default to 0/** use serialVersionUID from JDK 1.0.2 for interoperability */
private static final long serialVersionUID = -6849794470754667710L;
Beware of the Comment?
- We should only comment what clarifies the code.
- An ill-formed comment will only add to confusion. So, don’t comment which adds no value or already states what code already does.
- Code changes happens pretty fast, whilst comment move very slow. Comment put in for some relevant scenario might not be valid now. Comments become stale very quickly.
- Try to refactor the code structure or naming before you think about adding comments.
TL;DR Code is dynamic, it changes often. But, comments are slower to change. Comment become STALE very quickly.
Go to Sixteenth Step
Go to the Eighteenth Step.
References:
- 97 things Every Programmer Should Know ~ Git Book
- 97 Things Every Programmer Should Know ~ Paperback
- Self-Documenting Code ~ Wiki.c2
- How to write Doc comments for Javadoc Tool ~ Oracle