Chapter 4: Comments [Slide]
Don’t comment bad code—rewrite it". Brian W. Kernighan
Clear and expressive code with few comments is far superior to cluttered and complex code with lots of comments
prefer using separate function instead of commenting on if statement with multiple conditions
copyright
- function return intention
- comments to show eligible format patterns
important decisions that can be questionable by other programmers
when you don't have access to api and, you are just consumer of it and there need to be some clarification for it
eg. SimpleDateFormat is not thread safe, so we need to create each instance independently.
Don't run unless you have some time to kill.
It's okay to put todo comments when you don't have a good solution at the moment
indicate higher importance of notice
public api's must have java docs
eg. putting in comments for catch in try/catch blocks, just to satisfy IDE inspector.
Don't repeat code in comment, add something that has more value and meaning
comment should describe code accurately, otherwise it will mislead other programmers
Not all functions and variables should have java doc, it will just clutter up the code
log of changes to code should be maintained in version control system, not in code
commenting something that we already know about code is called noise
eg. // this is default constructor
copy pasting variable name in comment is a horrible scray noise!
eg. section comments, if statement comments
eg. // Actions //////////////////////////////////
separate your code into functions instead of commenting closing braces eg.
for(~) {
while(~) {
if() {
} // if
} // while
} // for
use version control instead of adding author name at top of classes
leaving commented out code is not a good practice anymore because we have VCS now.
If you want to put HTML docs, make sure your tool is displaying human readable format
referencing global configurations and information in a local function will quickly turn it into a lie when those information changes
Don’t put interesting historical discussions or irrelevant descriptions of details into your comments.
- The connection between a comment and the code it describes should be obvious
- The purpose of a comment is to explain code that does not explain itself. It is a pity when a comment needs its own explanation.
Short functions don’t need much description.
nonpublic code doesn't need javadocs for all single parameters