Are comments needed in your programs? If your code is very clear and expressive, then you won’t ideally need comments. By naming your identifiers correctly you can avoid the need for comments in lot of places within your code. So why learn about writing good comments? Due to reasons including the limitations in expressiveness of a programming language, we may have to still use comments, and for these use cases we will need to learn to write good comments.
Good comments include legal comments like copyright and authorship, informative comments that provide additional useful info regarding the usage, explanation of intent, extra clarification, warning of consequences, TODO comments, amplify the importance of something and Javadoc in Public APIs. However you should try to explore if any better and alternatives exist and whether it will be applicable for your use case. For instance, well written unit tests can even avoid the need for JavaDocs.
Bad comments include incomplete comments added just because you feel or the process requires it, redundant comments that are not more informative than the code, misleading comments that are not fully accurate, mandatory comments as a rule for functions, variables etc., journal or change log comments or attributions or commented out code which are all no more required with the use of source control systems, overuse of position marker comments, closing brace comments to cover-up larger functions, comments with too much information, comments with unobvious connection with code where comment itself will need as explanation and even javadocs in non-public code.
Code is always the truth. You can also supplement it with well written unit tests to explain the usages. Well written unit tests can even avoid the need for JavaDocs.
It is better to have not comments at all than inaccurate comments, as inaccurate comments may mislead. There are many reasons for its inaccuracy including comments not always following the code changes and evolution.
Don’t write bad code and spend time in explaining it through comments; instead spend extra time in writing good code and less time for writing comments. Clean code with fewer comments is always better that bad code with lots of comments.
When writing legal comments we should try not to put everything into comments; instead we should try to refer to standard license or other external documents.
HTML Comments make the code difficult to read; if the comment will be extracted by a tool to show in a webpage, the tool should do the formatting and not the programmer.
You should not comment about some other parts on the system from a comment as there is no guarantee that this comment will be updated when the other part is modified.
This note is based on the book “Clean Code” by “Robert C. Martin”. The chapter ‘Comments’ explains all these tips in detail along with examples.
For syntax and rules for comments in Java, refer to javajee.com/comments-in-java.