XNSIO
  About   Slides   Home  

 
Managed Chaos
Naresh Jain's Random Thoughts on Software Development and Adventure Sports
     
`
 
RSS Feed
Recent Thoughts
Tags
Recent Comments

Inline Comments in the Code is a Smell, but Document the Why

Thursday, March 7th, 2013

Is writing inline comments always bad? Are comments really evil? I keep getting these questions over and over again.

Often you see code like this:

// If the item is taxable, get the taxed amount using tax calculator
if( objItem.bTaxable )
{
	objItem.fTax = objCalculator.TaxForLocal(objItem.fItemRate);
}
 
// Additional tax is applicable if the item is an imported one
if( objItem.bImported )
{
	objItem.fTax += objCalculator.TaxForImported(objItem.fItemRate);
}
 
// Add tax to item rate
objItem.fTaxedRate = objItem.fItemRate + objItem.fTax;
 
// Return the final amount
double fFinalAmount = objItem.fTaxedRate * objItem.nNumberOfItems;
return fFinalAmount;

What is the real value of these comments?

When I see stuff like this, I usually tell people

When I was learning programming, I was thought that great programmers write great comments. These days I tell people lousy programmer write comments.

Immediately people who write inline-comments get defensive. And that’s completely understandably. I don’t think we’ve really explained our rationale for making such a ridiculous statement. So let me step back and explain the rationale.

Folks in the extreme-programming community will tell you:

Comments are often used as deodorant. Comments represent a failure to express an idea in the code. Try to make your code self-documenting or intention-revealing. When you feel like writing a comment, first try to refactor so that the comment becomes superfluous.

deyo_toilet

Most people will also tell you, that the biggest problem with comments is that they soon become outdated. The original intent of the person writing the comment was to help a developer who comes later to understand the code better. But unfortunately over a period of time, the comments get outdated and it adds more to the confusion. Speaking to many programmer, they simply delete or ignore the comments because they find them ambiguous. Even though the person who wrote the comments wrote them with a good intension, one needs to ask if it really solved any problem?

And then they question, why not put the same effort and time to write well-crafted code so that comments are never required? Is it impossible to do so?

While this argument is a good one, I find it hard to connivence people just based on this argument.

I’ve found the following approach work really well for me. First let’s understand why programmers write comments. Based on my experience, programmer write in-line comments for 3 different reasons:

  1. To explain what the code does
  2. To descrive how the code does what is does
  3. Why the code is written the way its written

If you think about it, the “what” and “how” of the code should really be expressed by self-documented code. IMHO its simply a failure on part of the programmer if they cannot express the “what” and “how” in the code itself.

However the “why” is little bit more tricky. It’s a reminder, telling us: “Hey, you are doing something complicated and someone else will not understand why. Even if you wrote a comment, they might not necessarily understand it.” At this point I might stop and see if there is a better way to design/model/code this, such that the why becomes obvious via the code. This is certainly more challenging and time consuming than to write a comment and moving on. However this short-term hack might bite me back. Luckily, most often than not, I can find a way to avoid the comment. But there are special cases when I need a comment to explain the why. Let’s see a few examples:

  • There is a bug in the underlying framework/library I’m using. Searching on the net, I found the bug report and a workaround. Looking at just the code might not help someone understand the need for the workaround. Generally I would write a small comment saying Workaround with the version number of the framework/library and add the link to the workaround and continue. In future, someone can remove the workaround & delete the comment if the issue is fixed.
  • I’m implementing a complex algo and its not common that everyone understands it. I would add a link to the Algo description (rather than duplicating the algo description in the code. DRY principle applies to comments as well.) and continue with my coding.
  • And so on…

So think again before you leave a comment 😉

When Should We Encourage Developers to Write Comments?

Sunday, May 15th, 2011

Many people will argue that there is more badly written code than good code. And its important to write comments to avoid these situations. Therefore we should encourage (force) people to write comments.

IMHO they are absolutely right that today many project suffer from poorly written code without any (good) comments. However every team I know, that suffers from this problem, has always been told (forced) to write comments. In spite of the emphasis on writing comments it has not really helped them.

I usually ask:

By asking developers to write comments are we really addressing the root of the problem?

.i.e. developers don’t invest quality time to write self-documenting code; code that clearly communicates its intent and does not require the deodorant of comments.

May be its time to try something different?

I have seen this myself many times, when we emphasize & educate the team on how to write clean code and ask them to stop wasting time writing comments, the code starts to communicate lot better. Its lot more maintainable. Also we have found that writing automated tests is a great way to document your intent as well.

This is how I would explain the concept Comments Smell to a team:

Writing comments that explain “how” or “what” the code does, what it does, is evil IMHO. Comments (esp. about what and how) is a clear failure to express the intent in code. Comment is a deodorant to hide that failure (smell).

  • If developers don’t invest time to write clear code, what is the guarantee that they will write clear comments?
  • Is doing a mediocre job at both (comments and code) better than doing a great job at just Code?
  • Will it actually be more productive to do both or just one?

Remember the biggest problem with comments it that they fall out-of-sync with code very soon. So its not just about the extra investment to write good comments, but also the investment to maintain them.

One has to think hard to write code that expresses intent rather than write some sloppy code with poor abstractions and get away (washing their hands off) by writing comments. Developers have to take responsibility for writing code that others can easily understand.

Having said that, there are times when “the why” (why we are doing something in the code, a particular way) is not apparent by just looking at the code. So if we don’t find a suitable way to communicate “the why” through code, comment is the fall back option.

Note that comments are a fall back option in “the why” case rather than a default option.

Are comments Evil?

Wednesday, August 19th, 2009

Today @Directi we had a few freshers from Universities come down for an interview. As part of the interview process, I presented on Code Smells. During this I was thrashing the whole “write good comments” universal best practice.

During this Ramki was sitting and he silently wrote me an email asking “Are comments evil?” His email follows:

Naresh,

Can you please opine if comments are bad in the following scenario:
(For this project dojo is a dependency and is not owned/maintained by the guys using it to write this code)

this.show = function(){
    this.view.show();
    //this is a hack, dojo seem to have an issue in rendering
    //dynamically/programmatically generated widgets.
    //We *should* call resize() to ensure that the widget is appropriately rendered
    this.view.resize();
}

—- Vs. ——-

this.show = function(){
    this.view.show();
    this.view.resize();
}

In the later case where comments are removed or say never written, though the user understands that you are resizing he would still be wondering why am I calling resize() when I am just showing..?

This is a great question Ramki.

I always say that comments are evil and we should not write comments. Also the first thing I do when I see some code is delete all the comments in it. This is an over generalized comment.

What I really mean:

Writing comments that explain “how” or “what” is evil. Comments (esp. about what and how) is a clear failure to express the intent in code. Comment is a deodorant to hide that failure (smell). However sometimes “the why” is not apparent and if you don’t find a suitable way to communicate that through code, comment is the fall back option. Note that comments are a fall back option rather than a default option. More on this…document the why.

At times, one has to think hard to write code that expresses intent rather than write some sloppy code with poor abstractions and get away by writing comments.

In my Self Documenting Code blog I show a similar example and explain the thinking process.

In case of your code I could write it as follows:

this.show = function(){
    this.view.show();
    reRenderDynamicallyGeneratedWidgets_dojoHack(this.view);
}
 
function reRenderDynamicallyGeneratedWidgets_dojoHack(view){
    // Link describing this bug and the workaround.
    view.resize();
}

This is really pushing it, but I hope you understand where I’m heading with this.

Self Documenting Code Example

Saturday, November 8th, 2008

Yesterday a colleague @ Directi was writing some code and was very unhappy about the code. He was not sure how to write the following method without having to add a comment to explain the rationale behind the code’s logic.

1
2
3
4
5
6
private HttpSession renewSession (HttpServletRequest request, HttpServletResponse response)
{
  HttpSession session = webUtils.getSession(request, response);
  session.invalidate();
  return webUtils.getSession(request, response);
}

The method name expressed what the code was doing (renewing an existing session) but the “why” it was doing what it was doing was missing. The why is very important for someone to understand. This method was invoked from the following method:

1
2
3
4
5
6
void createAuthenticatedSessionUsingAuthenticatedEntity (HttpServletRequest request, HttpServletResponse response)
{
  HttpSession session = renewSession(request, response);
  AuthenticationInfoBean authInfoBean = authUtils.getAuthInfoBean (request);
  session.setAttribute(getAuthenticatedUserBeanKey(), authenticatedBeanCreator.create(authInfoBean.getUsername(), authUtils.getValidatedEntity(request)));
}

One option was to rename renewSession method to renewUnAuthenticatedSessionToEliminateSesionFixationByInvalidatingSession. But in the context where this method was used, it would be too much noise. Not always I’m interested in how and why the session is renewed.

Another option is to write a JavaDoc for the renewSession method. Personally I hate JavaDocs and I was interested to find a way to eliminate that. So I asked the developer to first write the JavaDoc to express what he wanted to express. He wrote:

1
2
3
4
5
6
7
8
9
10
11
12
/**
* This method retrieves the unauthenticated session, then invalidates the session to eliminate session fixation issue and creates a new authenticated session.
* @param request HttpServletRequest
* @param response HttpServletResponse
* @return HttpSession Authenticated Session.
*/
private HttpSession renewSession (HttpServletRequest request, HttpServletResponse response)
{
  HttpSession session = webUtils.getSession(request, response);
  session.invalidate();
  return webUtils.getSession(request, response);
}

Now looking at the comment it was easy for me to figure out how to write the code such that the comment is not required. This is what we ended up creating.

1
2
3
4
5
6
7
8
9
10
11
private HttpSession renewSession(HttpServletRequest request, HttpServletResponse response)
{
  HttpSession unauthenticatedSession = webUtils.getSession(request, response);
  invalidateSessionToEliminateSesionFixation(unauthenticatedSession);
  return webUtils.getSession(request, response);
}
 
private HttpSession invalidateSessionToEliminateSesionFixation(HttpSession session)
{
  session.invalidate();
}

OR

1
2
3
4
5
6
private HttpSession renewSession(HttpServletRequest request, HttpServletResponse response)
{
  HttpSession session = retrieveUnAuthenticatedSession (request, response);
  eliminateSesionFixationByInvalidatingSession (session);
  return newlyCreatedAuthenticatedSession (request, response);
}

Again its arguable if writing code this way is much better that writing a small JavaDoc comment. As a rule of thumb, I always prefer self-documenting code over code which needs comments to support it. The real problem comes from the fact the comments soon fall out of place with the code. And why spend all the extra time maintaining code, its comments and also making sure they are in sync.

    Licensed under
Creative Commons License