This post is a summary of Chapter 4 of the Clean Code book by Robert C. Martin. Chapter 4 of Clean Code delves into the importance of writing meaningful comments and provides examples of good and bad comments.
- Good code should be so clear and expressive that it does not need comments at all.
- Truth can only be found in the code, only the code can truly tell you what it does. It is the only source of accurate information.
- Comments are sometimes necessary, but you should expend significant energy to minimise them.
- Explain your intent through code. You can do this by rewriting your code and turning it into a function with a descriptive name that says the same thing as the comment you want to write.
// Check to see if the employee is eligible for full benefits
if ((employee.flags & HOURLY_FLAG) && (employee.age > 65))
- Some comments are necessary. Examples of these are Legal comments such as copyright or authorship comments.
- Comments can explain intent. These comments go beyond providing useful information about the implementation, but provide the intent behind a decision.
- Comments can be helpful to clarify the meaning of some obscure argument or return value
- TODO comments have some value, scan through your code regularly and remove the ones you can.
- Comments can be used to amplify the importance of something that may otherwise seem inconsequential.
- Comments can be used to warn other programmers about certain consequences.
- Redundant comments. A comment that is less precise than the code or does not provide intent, rationale or simply restates the obvious.
//The day of the month
private int dayOfMonth;
- Misleading or Inaccurate comments.
- Commented out code. There’s no need to comment out code, remove it. The version control system will remember it for you and make it available if you ever need it again.
- Comments that don’t appear near the code they describe. Don’t offer system wide information in the context of a local comment.
- Inobvious connection. The reader must be able to read your comment and understand what it is talking about.
- Comments that provide too much information