What are your best practices for comments? When should they be used, and what they should contain? Or are comments even needed?
相关问题
- Using XPath to access comments a flat hierachy
- should I write more descriptive function names or
- Python Encoding Comment Format
- How to increase mysql table comments length?
- How to ignore unassigned new in ReSharper?
Ideally your program can communicate with the reader in code and not in comments. The ability to write software that other programmers can quickly understand separates the best programmers from the average in my opinion. Typically, if you or your colleagues cannot understand a section of code without comments, than this is a "code smell" and refactoring should be in order. However, there will some archaic libraries or other integration that a few comments to guide the average developer is not necessarily bad.
Just some remarks:
Comments are important for everything that can not be easily inferred from the code (e.g. complex mathematical algorithms).
The problems with comments is, that they need to be maintained like the code but often are not maintained at all.
I don't like comments like this:
Better:
Now the code tells the whole story. No need for a comment.
In school, the rule was to comment everything, so much so that comments outweigh code. I think that's silly.
I think comments should be used to document the "why" behind code, not the "how"... the code itself explains the "how". If there's an operation that isn't really clear as to why it is done, that's a good place for a comment.
TODO's and FIXME's sometimes go in comments, but ideally they should go in your source code management and bug tracking tools.
The one exception of where I don't mind seemingly useless comments is for documentation generators, that will only print documentation for functions that are commented - in that case, every public class and API interface needs to be commented at least enough to get the documentation generated.