The Paradox of Code Comments
We all know that comments are very important in any programming language. And who hasn’t come across code that was impossible to understand, even if it was written by yourself just six months ago? :)
But should we really use comments between the lines of our code? Note that I’m not talking about comments typically used to describe what a function does, which are compiled into JavaDoc or something similar.
The clarity of code is essential; no one questions that. Any programmer who comes across your code should be able to understand it within a few minutes and without much effort. But could using comments be a sign of something wrong?
But how can explaining your code be a bad thing? In the book Clean Code, Uncle Bob says that readable code should be like good prose. Each line of your code should, by itself, tell a piece of the story. The point here is that if you need to comment on your code to make it easier to understand, perhaps it needs to be refactored.
Let’s look at an example:
Reading the comments, we can clearly understand what each line does. But what if we refactor the code, extracting each part into a private function and giving each function a descriptive name? Check out the modified code:
So, what do you think? Do you prefer to comment on your code or extract everything into smaller functions? Share your opinion in the comments.
#Java #CleanCode #Refactoring