Home
About
Contact
Monday, August 03, 2009

It's tempting to just leave this blog post with that statement only :-) I will however explain this a bit further for those of you who either are forced to write comments (like by your boss or a policy at your company), or actually believe a lot of comments in code increase readability and ease maintenance.

I'm not trying to be sarcastic, I just believe 100% in code and not in comments. In .NET and most other OO languages there are two types of comments. The first type is the one you write in your code to explain what your code does. Like this:

//Calculate interest
double amount 
    = balance * Math.Pow(1 + (annualPercentage / 100) / 365, days)
      - balance;

How do you replace this comment with code? What about this:

double amount = CalculateInterest(balance, annualPercentage, days);

Whenever you come across comments like the above, I encourage you to refactor by replacing comments with code. Often you don't even have to extract a method like above, but just give better names to variables.

The second type of comments is the ones you use to generate API documentation:

/// <summary>
/// Calculate interest
/// </summary>
/// <param name="balance">Current balance of the account</param>
/// <param name="annualPercentage">Annual percentage</param>
/// <param name="days">Days to calculate interest for</param>
/// <returns>Interest amount</returns>
public double CalculateInterest(double balance, 
                                double annualPercentage, 
                                int days)
{

Almost on every project I've been on we've had these comments/documentation. Also, on the same projects they've never been used for anything useful. I've actually forced devs to do this myself! If you're creating a product/framework to be used by other devs, writing this type of documentation makes sense. If you don't, it makes no sense! I used to do this just to satisfy my own satisfaction of generating a chm file and see that all my methods and classes was documented. That was about it. I never used it once! It's much easier to look in the code than to look at the API doc.

The worst thing about this type of documentation is that it clutters your code and makes the code hard to read. A class with 50 lines of code becomes 100 lines with comments. As a practice, try to remove all comments and see if it's easier to understand and read the class. I strongly believe it is. If not, it's a code smell and you should refactor your code! Comments should not be used to explain bad code.

When I talk to people about comments in code I often ask them two questions:

Do you think it's hard to maintain code?

How hard to you think it is to maintain comments?

If you change your code, do you also make sure to check if the comments are still correct after you've done the changes? Most people don't and you shouldn't really need to worry about it. Outdated comments can create confusion and bugs just because someone forgot to update them.

Monday, August 03, 2009 2:11:00 PM (W. Europe Daylight Time, UTC+02:00)
Couldn't agree more: http://blog.fohjin.com/blog/2009/7/3/Hey_Developer_the_product_you_create_is_your_code

-Mark
Monday, August 03, 2009 3:41:57 PM (W. Europe Daylight Time, UTC+02:00)
My thoughts exactly :-)

However, the objections to remove these comments, or even not write them in the first place, never stops.

The first one popping to my mind is: "But, if you don't want to see them, you can collapse them and problem solved."

How do I successfully challenge that?
Monday, August 03, 2009 6:37:15 PM (W. Europe Daylight Time, UTC+02:00)
Thomas,

I've given up on Mort a long time ago ;-)
Tuesday, August 04, 2009 2:42:14 PM (W. Europe Daylight Time, UTC+02:00)
:-) This is definitely an on going debate that has been lingering and rumbling for many many years. However I'm afraid I'm a comment advocate! Predominately the reason is that the no comment process is dependent on the correct implementation the first time (or you have access to the programmer at a time they actually recall what they wrote - i.e. within 6 months). Your example is certainly nice and neat and gives a compelling argument - however I've been dealing with code that was initially written 10+ years ago and had many hands in the support pot dealing with it. More often than not the comments give the 'intent' of the programmer at the time, rather than what they are actually doing! The key to me is that comments shouldn't be an either or

* Read the comments to understand what the module is doing
OR
* Read the code to understand what it is doing

The code should be read (code + comments) to determine what the programmer was intending to be doing and find any differences between the comments and the actual implementation. The intent of code rarely changes, however the implementation often changes.

Finally you didnt mention that the API documentation has one useful side effect even if you don't have the compiled CHM (which most people dont do) is that Intellisense displays the information in the tool tip. This can be quite helpful when using code you are not 100% familiar with.

Any way - good article :-)
Tuesday, August 04, 2009 3:09:09 PM (W. Europe Daylight Time, UTC+02:00)
I agree and stress self-documenting code over code comments with my team. There are worse examples of superfluous comments than the one Jon gives, and worse side effects. I've seen comments that just state the obvious, for instance in a loop through Orders, I might see a comment saying "looping through orders". The worse side-effect of over commenting is that when the code changes people seldom change their comments, so you have comments that don't even describe the behavior, which creates confusion.
Tuesday, August 04, 2009 4:59:56 PM (W. Europe Daylight Time, UTC+02:00)
The biggest problem with commenting the obvious or commenting where self documenting code could be applied is that when you do need to use a comment (because you cannot do everything in code) it blends in with the other none meaning full comments and thus a very important comment gets lost.
Tuesday, August 04, 2009 11:58:18 PM (W. Europe Daylight Time, UTC+02:00)
Thanks for feedback, Jon! :)
(Just in time when I'm writing blog entry about code documentation)

Two things

1) I consider code comments and documentation as different things. Code documentation is powerful think in Visual Studio as it integrates to IntelliSense and can be source of compiled documentation. You may think that inside same team code documentation is not important but my experiences show something else. When you have to return to code you wrote months ago you are suddenly both developer and client of your old code. I think this day you thank God if you wrote code documentation. Question is not if there is point to document your code - question is how to write useful documentation.

2) I agree that pointless code comments are bad thing. They can cause more harm than good. But there are cases when code comments may help a lot. I think Code Complete 2 (the best book I have read this far about coding) illustrates these issues best.
Wednesday, August 05, 2009 9:01:05 PM (W. Europe Daylight Time, UTC+02:00)
I too am a comment advocate where they are used properly. The problem with this type of post is that it doesn't explore the argument fully. It always mentions the API documentation style comments. They also always come up with things like your first example (where I couldn't agree more - this comment is pointless).

One they miss out is the explanation comment. Let's say that the calculation for an interest payment in a method is slightly different from what you would expect to see and that there are no comments. Does this mean that there is a bug? Or does the company actually use a different method for a reason. A good comment would be: // calculates using non-standard interest calculation as per.....

The other thing I dislike about the anti-comment movement that is around at the moment is that many are 100% certain that there should be exactly zero comments. "If the code is well written, you don't need comments because you can just read the code". I disagree strongly here. My belief is that you should not have to read and understand a whole bunch of methods when trying to maintain the code. I would much rather have a comment to read in five seconds than have to spend ten minutes reading. My time is more valuable than that and it would be a disservice to my customers to make them pay for such inefficiency.
Bob Saggett
Thursday, August 06, 2009 1:50:01 AM (W. Europe Daylight Time, UTC+02:00)
I think maybe you are used to see poor comments.

So how do you explain complex algorithms in code? You have to have things like Lists, Nodes, etc. But explaining why a page is being split in 2/3 rather than some other strategy...

Comments are the only way to explain logic reasons - not the logic that is preset.

I can SEE that you did something - but not understand the WHY.

WHY you do something or chose a particular algorithm in the comments can save someone hundreds of hours from trying to change that algorithm years later only to learn what you already knew in the first place - it didn't work for this problem.

Yes, you can put them in design docs, wikis, etc. But the developers are going to be looking at the code. If they see something that they think is a poor algorithm choice they will want to change it. I have seem some companies where the checkin - revert cycle on particular subsystems is quite large because every new programmer coming in thought they knew a better algorithm only to be shot down with actual runtime tests.

You can delete those comments above, none of them help me understand why you were doing anything anyway.
Thursday, August 06, 2009 7:32:18 AM (W. Europe Daylight Time, UTC+02:00)
Thanks for all your feedback guys!

I'm not saying never use comments. I'm saying replace them with code where possible. Jason's example with complex algorithms I completely support, thought I also suggest looking into how to simplify this code. Sometimes complex code remains complex because the problem being solved IS complex.

My main point is to not litter your code with comments, because they'll be in your way. Use comments where needed and focus on naming variables, methods and classes properly to avoid unnecessary comments.

Gareth have a point in regards to intellisense, which is nice sometimes. Though I've noticed I'm looking for intellisense when the name of that property, class or method don't communicate its intent properly. Naming is hard. Use this type of comments when you're just unable to name things better, but don't avoid focusing on naming just because you can add its intent in comments.
Thursday, August 06, 2009 8:07:18 PM (W. Europe Daylight Time, UTC+02:00)
Comments in code are simply a path into the land of DRY-Violation. They should be used where appropriate and where it isn't possible to express the intent clearly through code. I agree with Jon's argument wholeheartedly--expend effort on writing clean, intelligable code long before writing comments that may just be an excuse for "refactoring laziness".
OpenID
Please login with either your OpenID above, or your details below.
Name
E-mail
(will show your gravatar icon)
Home page

Comment (Some html is allowed: a@href@title, b, blockquote@cite, em, i, strike, strong, sub, sup, u) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

Live Comment Preview
RSS RSS - Comments Twitter LinkedIn
         
SEARCH
 
 
         
TOP POSTS
   
         
NAVIGATION
   
         
CATEGORIES
  .Net (61) ADFS (3) Agile (31) Ajax (5) Architecture (20) Articles (1) ASP.NET (7) ASP.NET-MVC (1) Blogging (12) Books (2) BPEL (1) CleanCode (1) CloudComputing (7) Community (5) CSharp (11) DasBlog (5) Database (2) DDD (5) Deployment (17) DSL (1) Events (38) ExtremeProgramming (6) Fun (6) Gadgets (4) IIS (10) InfoQ (4) Java (2) Kanban (1) Lean (3) Linq (2) MemoryLeaks (5) Microsoft (37) MVC (1) NDC (2) NNUG (37) Other (10) Patterns (9) Performance (3) Scrum (17) Security (7) ServiceBus (1) Silverlight (4) Software (19) TeamManagement (12) TechEd (7) Testing (5) Tools (25) TvGuide (1) Vista (15) VisualStudio (16) WCF (8) Web (16) WebDeploy (2) WIF (3) Windows (10) WiX (9) Work (18) Workflow (3)  
         
ARCHIVE
   
         
BLOGROLL
   
         
ON THIS PAGE...