Feeds

Sweet, sweet smell of comments in code?

Extreme Programming breeds overreaction

The Power of One Brief: Top reasons to choose HP BladeSystem

Arguments rage over the importance of adding comments to your code versus the importance of writing clear code that speaks for itself, thereby potentially eliminating the need for comments. The dichotomy boils down to this: writing comments versus writing self-commenting code, as if comments and clear code are somehow mutually exclusive.

Before I get into the cut and thrust of this debate, it's worth stating that the subject of comments is less of an important issue than writing good code. While comments have value, if the code is crufty and convoluted, adding a few paragraphs of comments - while well intentioned - are only likely to add to the noise.

The Extreme Programming movement, back in its heyday, popularized the notion that comments in code are bad, taking the position that if you see a comment then it must be a "code smell" and you should grab your pair-programming buddy and refactor the stinky code immediately. The term used was "coding by intention" - writing code that so obviously communicates its method and purpose that it doesn't need to be commented.

So instead of this:


int x=0;   // day of month, 0 if not found
for (Rabbit rabbit : warren) { // check for a white rabbit
    if (Color.WHITE.equals(rabbit.getColor()) {
        x=1;   // First day of month,
        break; // so hop out of loop
    }
}
// Show msg indicating start of month or not:
System.out.println( (x==1)?
    "It's the first day of the month!" :
    "Sorry, it isn't the first day of the month."

You have this:

boolean firstDay = isFirstDayOfMonth();
showDayOfMonthMsg(firstDay);

(and the obvious extracted methods...)

Note that isFirstDayOfMonth() isn't called something like checkForWhiteRabbit() because the "how" (or method) of determining whether it's the first day of the month is encapsulated into the method itself. This goes some way towards explaining why these are called methods.

The notion seems reasonable, and in fact it's a good guideline to follow - up to a point. As with many of its practices, XP spoiled a good guideline by taking it to extremes, turning the knob all the way up to 10: comments are a "code smell" and must be refactored out; if you spot a code smell, refactor it immediately.

But however vocally XPers argue against commenting - or over commenting - your code, the opposite camp can argue pretty loudly too.

Here are some of the arguments for comments in code:

  • Months later, someone will look at your unclear or uncommented code, they will go out, buy a shotgun and hunt you down.
  • Clear code conveys the "what" and the "how", but not the "why" - the crucial missing context that comments can and should supply. My personal answer to this argument is - if you'll excuse the book plug: write lightweight use cases (or user stories) and tie them closely to the objects. That gives you the "why" with traceability and a method of driving functional/unit tests from your use cases, for very little extra effort.
  • Sometimes you need to work around an API glitch, or your code steps outside the obvious, and you want to communicate why.
  • If you're writing an API, the public methods need to be liberally commented so, for example, you can give the Javadoc tool something decent to munch on.

Sounds reasonable? Here, then, are some of the arguments for not adding comments:

  • They are not provably correct - if you write a unit test instead of a comment, though, the test is correct. Note this argument is logical bunkum, because a test's pass/fail isn't the same as provable correctness. It's provable passing/failing - also important, but different.
  • A comment in code is a sign that the code isn't clear enough.
  • Comments become out of date because they don't fail at compile- or run-time like out-of-date code.
  • Sometimes comments are copied and pasted along with copied and pasted code. That means the code is then changed but the comments aren't, resulting in comments that essentially tell lies about the code.
  • Comments are often redundant, simply paraphrasing what the code already says ("// increment x").

Clearly, there are compelling arguments on both sides. But you should also be able to see a pattern emerge from the arguments. They're talking about particular conditions when the argument holds true.

So if it's only sometimes vitally important to comment your code or to write clearer code/tests instead of comments, why do the proponents of either side argue so vehemently for their cause? I'll delve further next time.®

Matt Stephens is co-author of Extreme Programming Refactored, which skewers XP like a rodent on a toasting fork.

The Essential Guide to IT Transformation

More from The Register

next story
KDE releases ice-cream coloured Plasma 5 just in time for summer
Melty but refreshing - popular rival to Mint's Cinnamon's still a work in progress
NO MORE ALL CAPS and other pleasures of Visual Studio 14
Unpicking a packed preview that breaks down ASP.NET
Secure microkernel that uses maths to be 'bug free' goes open source
Hacker-repelling, drone-protecting code will soon be yours to tweak as you see fit
Cheer up, Nokia fans. It can start making mobes again in 18 months
The real winner of the Nokia sale is *drumroll* ... Nokia
Put down that Oracle database patch: It could cost $23,000 per CPU
On-by-default INMEMORY tech a boon for developers ... as long as they can afford it
Another day, another Firefox: Version 31 is upon us ALREADY
Web devs, Mozilla really wants you to like this one
Google shows off new Chrome OS look
Athena springs full-grown from Chromium project's head
prev story

Whitepapers

Implementing global e-invoicing with guaranteed legal certainty
Explaining the role local tax compliance plays in successful supply chain management and e-business and how leading global brands are addressing this.
Consolidation: The Foundation for IT Business Transformation
In this whitepaper learn how effective consolidation of IT and business resources can enable multiple, meaningful business benefits.
Application security programs and practises
Follow a few strategies and your organization can gain the full benefits of open source and the cloud without compromising the security of your applications.
How modern custom applications can spur business growth
Learn how to create, deploy and manage custom applications without consuming or expanding the need for scarce, expensive IT resources.
Securing Web Applications Made Simple and Scalable
Learn how automated security testing can provide a simple and scalable way to protect your web applications.