Notes Of Clean Code — Chapter 4 (Comments)

Elif Burçak Namver
Odeal-Tech
Published in
4 min readJan 2, 2023

Previous Chapter : Functions

Our purpose for using comments is because we can’t express ourselves enough with code. But comments are always failures. Because we don’t know how to express ourselves without them.

So, If you find yourself in a position where you need to write a comment, back to code and try to express yourself in code.

https://hilton.org.uk/blog/comments-bad.jpg

Code changes and evolves. Chunks of it move from here to there. But the comments can’t always follow them. And comments get separated from the code they describe. For example:

MockRequest request;
private final String HTTP_DATE_REGEXP =
"[SMTWF][a-z]{2}\\,\\s[0-9]{2}\\s[JFMASOND][a-z]{2}\\s"+
"[0-9]{4}\\s[0-9]{2}\\:[0-9]{2}\\:[0-9]{2}\\sGMT";
private Response response;
private FitNesseContext context;
private FileResponder responder;
private Locale saveLocale;
// Example: "Tue, 02 Apr 2003 22:18:49 GMT"

Normally the comment describe the HTTP_DATE_REGEXP constant. But other instance variables added. And the comment wasn’t updated.

One of the more common motivations for writing comments is bad code. We know the code is a mess. And we want to add comments to describe ourselves. But It’s not good way. Clear and expressive code with few comments is better than complex code with lots of comments.

Of course the code always isn’t enough for explanation ourselves. But there is a way. Look those two code below, which would you rather see?:

// Check to see if the employee is eligible for full benefits
if ((employee.flags & HOURLY_FLAG) &&
(employee.age > 65))

or

if (employee.isEligibleForFullBenefits())

Good Comments

Some comments are necessary and beneficial.

For example, copyright and authorship statements are necessary and reasonable things to put into a comment at the start of each source file:

// Copyright (C) 2003,2004,2005 by Object Mentor, Inc. All rights reserved.
// Released under the terms of the GNU General Public License version 2 or later.

Sometimes we add //TODO comments for to do notes:

//TODO-MdM these are not needed
// We expect this to go away when we do the checkout model
protected VersionInfo makeVersion() throws Exception {
return null;
}

It looks like a good comment but still TODO comments are not an excuse to leave bad code in the system.

If you are writing a public API, then you should write good javadocs for it. But Javadocs can be misleading and dishonest as any other kind of comment.

Bad Comments

If you decide to write a comment then spend your time and write a best comment. Look at this example, author didn’t give much attention and his mumbling:

public void loadProperties() {
try {
String propertiesPath = propertiesLocation + "/" + PROPERTIES_FILE;
FileInputStream propertiesStream = new FileInputStream(propertiesPath);
loadedProperties.load(propertiesStream);
} catch (IOException e) {
// No properties files means all defaults are loaded
}
}

What does this comment mean ? Probably, if we get IOException, there was no properties files and all defaults are loaded. But how ? Were they loaded before the call to loadProperties.load? Or did loadProperties.load catch the exception, load the defaults, and then pass the exception on for us to ignore? Or did loadProperties.load load all the defaults before attempting to load the file? Or — this is the best scary scenario- he/she wrote this comment and he/she would come back and load the defaults.

See the following code example, reading is a waste of time:

// Utility method that returns when this.closed is true. Throws an exception
// if the timeout is reached.
public synchronized void waitForClose(final long timeoutMillis)
throws Exception {
if (!closed) {
wait(timeoutMillis);
if (!closed)
throw new Exception("MockResponseSender could not be closed");
}
}

The code is informative enough. No comment required.

What about these following Javadoc comments ? They explain nothing.

/** The name. */
private String name;
/** The version. */
private String version;
/** The licenceName. */
private String licenceName;
/** The version. */
private String info;

Look carefully. Do you recognize copy-paste error? If authors aren’t paying attention when comments are written (or pasted), why should readers be expected to profit from them.

Look at the following code, The author may have written a comment first and then the code:

// does the module from the global list <mod> depend on the
// subsystem we are part of?
if (smodule.getDependSubsystems().contains(subSysMod.getSubSystem()))

Author should have refactored the code, so that the comment could be removed.

ArrayList moduleDependees = smodule.getDependSubsystems();
String ourSubSystem = subSysMod.getSubSystem();
if (moduleDependees.contains(ourSubSystem))

Sometimes programmers write comments on closing braces. This might make sense if your code is too long. But instead that try to shorten your function.

public class wc {
public static void main(String[] args) {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in))
;
String line;
int lineCount = 0;
int charCount = 0;
int wordCount = 0;
try {
while ((line = in.readLine()) != null) {
lineCount++;
charCount += line.length();
String words[] = line.split("\\W");
wordCount += words.length;
} //while
System.out.println("wordCount = " + wordCount);
System.out.println("lineCount = " + lineCount);
System.out.println("charCount = " + charCount);
} // try
catch (IOException e) {
System.err.println("Error:" + e.getMessage());
} //catch
} //main
}

Don’t do commented-out code.

InputStreamResponse response = new InputStreamResponse();
response.setBody(formatter.getResultStream(), formatter.getByteCount());
// InputStream resultsStream = formatter.getResultStream();
// StreamReader reader = new StreamReader(resultsStream);
// response.setContent(reader.read(formatter.getByteCount()));

When you see that commented-out code, what do you think? Do you courage to delete it ? You’ll think it’s important for deleting. In old times commented-out code was useful. But now we have a good source code control systems. Those systems will remember the code for us. Just delete it.

“Don’t comment bad code — rewrite it”
Brian W. Kernighan

--

--