
Clean code is all about making your code as readable and maintainable as possible. One important aspect of this is the use of comments. In Chapter 4 of the book “Clean Code” by Robert C. Martin, he discusses the role of comments in code and how they can be used effectively. Today I’m going to create a quick summary of this chapter and why I think it’s important. For a better understanding of Martin’s thoughts, I recommend reading his books!
Comments are an important tool for documenting and explaining the intent and functionality of your code. They can help others understand what your code is doing, especially if it is not immediately clear from the code itself. However, it’s important to use comments sparingly and only when necessary. Overuse of comments can make your code harder to read and maintain. Try not to be redundant.
One of the key points from Chapter 4 is that good code should be self-explanatory. This means that the code itself should be written in a way that is easy to understand, without the need for excessive comments. This can be achieved through the use of clear and descriptive variable names, as well as the use of well-organized and modular code.
Here is an example, where the code really explains itself:
//Incorrect way:
// Check to see if the employee is eligible for full benefits
if ((employee.flags & HOURLY_FLAG) &&
(employee.age > 65))
//Correct way:
if (employee.isEligibleForFullBenefits())
When comments are necessary, it’s important to make sure they are clear and concise. A good rule of thumb is to write comments that describe why the code is doing something, rather than how it is doing it. This helps to keep the comments relevant and focused on the overall goal of the code.
- Legal comments will be necessary at times as well.
- Other use comments are comments that give an understanding of potential warnings.
- Don’t comment out the code, delete it — it won’t get lost! Other developers often can refrain from deleting out older commented code, so we’re better off deleting it.
It’s also important to keep your comments up to date. If you make changes to the code, be sure to update the comments to reflect the new functionality. Outdated comments can be misleading and can cause confusion for other developers working with the code.
In summary, comments can be a useful tool for documenting and explaining your code, but they should be used sparingly. Good code should be self-explanatory, and clear and concise comments can help to provide additional context and understanding when needed. Remember to keep your comments up to date to ensure that they are accurate and helpful to others working with your code.