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.