Development

A Comment Is an Invitation for Refactoring

A comment is an apology for not choosing a clearer name, or a more reasonable set of parameters, or for the failure to use explanatory variables and explanatory functions. Apologies for making the code unmaintainable, apologies for not using well-known algorithms, apologies for writing ‘clever’ code, apologies for not having a good version control system, apologies for not having finished the job of writing the code, or for leaving vulnerabilities or flaws in the code.

A pretty purist view – but can we really go coding without comments? What about how code should tell you the how and comments should tell you the why?

Let us agree that most inline comments can be eliminated by refactoring the code itself (note the emphasis on most). Whenever you come across a comment in the code, ask yourself: could I refactor the code to remove this comment? The answer will be yes, in many cases.

And this is a great thing. Every comment that becomes part of the code will make refactoring more difficult – because when refactoring, not only the code, but the comment also needs to be changed. And we usually end up forgetting about them. In Clean Code the section on comments says:

The problem with comments is that they have no compile-time check and tend to be forgotten. It’s very easy to change your code but forget about the comments.

Almost all inline comments are ones that could be removed or moved while making the code more readable and easier to refactor.

Coding Without Comments?

Comments certainly have their use and place. A use case where they are invaluable are API documentation and explaining things that code just cannot convey (or it would be too complex). Here’s what Jeff Atwood says about coding without comments:

If your feel your code is too complex to understand without comments, your code is probably just bad. Rewrite it until it does not need comments anymore. If, at the end of that effort, you still feel comments are necessary, then by all means, add comments. Carefully.

Apart from documenting your public API, you should treat each comment as an opportunity to refactor your code, to make it even more readable, with or without the comment. Comments have their use and place – make sure it is a valid one before using them.

About Codacity Informatica Group  

We are at our heart, engineers who love change and delivery. That what makes us stand out. We recognize that systems must always start and end with clean code. CIG can power your software development transformation from ideation to execution and benefit delivery. We have more than 18 years of experience driving business change in many settings. We are ready to enable you today.