Disclaimer: I’m probably still considered Junior level at this point
Either way, I’ve seen both extreme ends of code lacking sufficient documentation, and code which has excessive documentation that doesn’t add anything to it.
- Obviously, it is a mistake to comment every single line of code you write. This has been my annoyance in a lot of code that I’ve inherited from previous employees. For example:
/* if local preferences is null /
if (LocalPreferences == null)
/ return /
/ if dynamic report is not null /
if (DynamicReportPanel != null)
} / if DynamicReportPanel != null */
this is a real section of code I’m maintaining… If your comment does not say anything more than the line of code itself would say if read out loud, then please don’t waste the time to say it (and my time in reading it)… I have had to go to the extreme and remove all comments from certain sections of code… and it actually did help readability…
The other extreme of not writing comments period, is just as bad. Consider the situation as well that I have inherited code written by a senior developer which is comment-less. The methods all have very logical, explanatory names, but when it gets down to the details of what’s going on, I’m left to read through and figure out what all of the rest is doing. Plainly and simply put, if you’re coding in a work environment, odds are that someone else is going to have to do bug fixes or other maintenance to the code that you wrote. Stepping into a piece of code, a developer won’t necessarily understand how your classes are structured, or even necessarily how your methods are put together.
I think the biggest problem I’ve been seeing with comments is the granularity of detail that they seek to explain. 99% of the time, you shouldn’t have to explain a single line of code, and if you do, you should probably see if there’s a more straightforward way to write it (in the examples, i do agree that some formulas are a pretty good candidate for the exception to the rule).
Sparse block comments can really help establish the functionality of a section of code without having to read and understand every single line detail of the process, giving a brief logical overview to someone who has never touched your code before, and as such, can become a sort of map for navigating to applicable sections of code, or to get one’s bearing within a particular segment. One of the comment-less pieces of code i received parses through a pretty complex tree without any note on what we’re looking for at any particular level.
IMHO, if you need to comment individual lines, try refactoring, but don’t neglect to give a generalized roadmap of what a particular chunk of code is supposed to accomplish…