I was reminded of a conversation Marshall and I had about comments when I read this post by Jesse Liberty.
The post gives an example of the reason your comments should explain why you're doing something, rather than how you're doing it.
At the end, Jesse argues that if your reader knows the language, your comments will be reduntant if you use descritptive names for methods and variables.
Lately I've been thingking a lot about how much I should be commenting. And whether or not I'm just stating the obvious.
Take this method for example.
public string GetRunTimeForAllCars()
{
IEnumerable<Car> listOfCars = listOfVehicles.FindAll(c => c is Car).Cast<Car>();
double totalRunTime = listOfCars.Select(t => t.RunTime).Sum();
return totalRunTime.ToString("f2");
}
I experimented with a few ways or writing the method out before I decided on this one.
I think it's pretty clear and doesn't need any comments to tell you what's going on.
What do you guys think?
Are comments always neccessary?
If somebody doesn't know linq, can they still understand what that code is doing?
Tuesday, October 25, 2011
Subscribe to:
Post Comments (Atom)
I disagree with the assertion that comments are redundant if one uses well named variables. I comment and I also name my variables and methods very well. I feel both are important.
ReplyDeleteIn your specific example, the method is very simple and well named. I would not have in line comments but I'd still have a method level comment block that quickly explains what the method does and what parameters it expects (none in this case obviously). Also, what will it return, and can it return null? This way consumers of the method don't have to read it to know these things.
It might be that this is too much, and admittedly, when things are named well, commenting is not needed as much, but I still do it.
The most common argument against commenting is that the comments become out of date as code changes and wrong comments are worse than no comments. While I agree that wrong comments are worse than no comments, I don't agree with the assertion that this is a good reason to abandon commenting. What about an alternative scenario where engineers change comments when they change the code the comments are commenting on. As professionals there is no excuse for us being lazy in this regard. I don't agree with the mentality that says "since developers don't keep comments up to date anyway, lets just not comment."
I find that I really like having intellisense on methods. In this particular case I would do something like:
ReplyDeletesummary:
Sums estimated run time for all Car items.
returns:
total run time as a formatted string
I agree with you that maintenance & refactoring should absolutely include comments. I think that comments should add to the overall picture and not clutter. One should not comment for the sake of commenting, the purpose should be to clarify.