If youre a programmer, there are plenty of practices to hate. Hard-coded values. Duplicate logic.
Complex inheritance hierarchies. But should code comments be on the list?Long ago, writing a comment was seen as a simple bit of good coding hygiene.
When you coded, you left brief, focused comments, like a park ranger setting tree markers while forging a new trail. Then Clean Code and agile programming burst into the mainstream. Purists shouted about the danger of bad comments covering loose and baggy code.
Suddenly comments were a coding failure, an anti-pattern, a collection of outright lies. More than a few working developers felt themselves backed into a corner.But is the choice really this stark?
Or is there a way to write code comments today and still respect ourselves in the morning? To size it up, lets consider the ways that comments corrupt codeand how even a bad comment can save lives.The first crime: Lazy commentsThe most frequent crime that developers commit in the name of commenting is simple using a comment to avoid programming effort.
For example, take this snippet of code, taken from a real-world application:double delta = h*h-r1*r1;double r2 = Math.Sqrt(delta);Even though the code operations in this snippet are easy to follow, the code meaning is as murky as a Seattle fog. But a developer whos written an obscure block of code like this can quickly paper over its poor quality by slapping on a comment that explains it:// Calculate side length using the Pythagorean Theorem// and put the value into variable "r2"double delta = h*h-r1*r1;double r2 = Math.
Sqrt(delta);This is the first problem with comments they open the door to bad habits. They tempt you off the virtuous high road of continuous refactoring, and down the easy path of describing sloppy code.In this example, there are plenty of ways to avoid the comment.
Heres one possible rewrite where variable names do the talking:double lengthSideB = Math.Sqrt( Math.Pow(hypotenuse,2) - Math.
Pow(lengthSideA,2);)Or, you could refactor the operation to a separate method, and let the method name do the talking:double sideA = Pythagoras.GetLengthOfSide(hyptenuse, sideB);Is this overkill for such a simple example? Obviously!
But this example illustrates one of the core strategy of clean coding take the meaning out of the comment and inject it into the names of variables, methods, classes, and interfaces. (For a more elaborate example, check out this commented version of a prime-number search routine, and its refactor.)Lazy comments arent just used to avoid refactoring.
Theyre also used to avoid thinking through a problem or finishing a job (think of the infamous //TODO). A particularly bad use of a comment is documenting strange behavior or unexpected limits in a code routine, without making any attempt to fix it.The second crime: Comments that lieFor many clean coding purists, eliminating lazy comments isnt enough.
Even comments that seem innocent are a risk, because they can contradict the reality of your code. In other words, comments introduce a type of duplication a human repetition of a computer-language solution. That means theyre subject to inconsistency, just like duplicated code in your application.
Another programmer might update the implementation without remembering to adjust the comments. This is particularly likely when a comment applies to many lines of code or is separated by some distance from its implementation. Developers get particularly sloppy with boilerplate like this:/** * Constructor.
* * @param name (required) brand name of the product. Must have * content. Length must be in range 1.
.50. * @param price (optional) purchase price of the product.
* @param units (required) number of units currently in stock. * Can not be less than 0.*/public Product(string name, decimal price, integer units) .
.Some companies mandate these comment blocks, under the assumption that more information means less ambiguity. This is true until the comment block is copied and pasted one too many times and becomes a new source of bad information.
False comments create a trap for the coders who follow. Believe a faulty comment, and you start a chain of bad assumptions that can lead to overlooking an existing bug or even introducing a new one.Everything liesComments are untrustworthy.
There are no unit tests that can guarantee their truth. But this is not a unique problem. In fact, almost everything can lie.
A typical coding project repeats itself in many different domains. There are design requirements, documentation, data schema all of which can contradict one another. And although every project needs to designate a single source of authority, it also needs to include these other ingredients that can come into conflict.
Consider an API document. You can build it with all the right types, members, and method signatures using reflection. Theres almost no opportunity for a lie to sneak in.
But after that, someone needs to write the descriptions that give the code structures meaning. The fact that API documents can lie is a source of frustration for developers working with fast-changing technology, but hardly a reason to abandon them.The problems dont stop with documentation.
Even if you replace every comment with carefully named variables and method names, those names can also be turned into lies by someone elses careless edits. In other words, the risk of believing a comment is real. But dont conflate the risk of using a comment with the risk of writing one.
Comments are lies tells us to stop trusting comments uncritically, not to stop writing them. Comments are a trail of breadcrumbsEven an incorrect comment isnt necessarily useless. Consider the following cryptic comment thats been buried in the open-source code to my favorite rhythm game for more than a decade:// to match ITG1's late arrows.
-KGlobalOffsetSeconds=-0.006This comment has earned a place in infamy because its exactly untrue a negative offset shifts a songs sync earlier, not later. And yet, this blatantly incorrect comment still conveys information that reveals the problem the game designers were attempting to fix and the flawed decision they made.
More importantly, it gives you insight into how you might compensate for what went wrong.Or imagine an example with regular expressions. If youve put one in your code, I hope you added a comment to explain its purpose.
But what if your comment lies in other words, the regular expression doesnt properly validate what you think it does? In this case your comment still has value because it records your intent, which is the only piece of information the coder fixing your bug will have to go on.Obviously, a comment that sheds partial light on a problem is inferior to clean, perfect code.
But not all developers write clean code, and most developers who do dont succeed perfectly all the time. Its hard to put yourself in the place of another person reading your work. One persons obvious is another persons obscure and that other person is you, next year.
I spent some time this weekend looking at very well-named, very clean, uncommented code implementing a research algorithm. Im high-level familiar with it, the guy sitting next to me was the inventor, and the code was written a few years ago by someone else. We could barely follow it.
Paul NathanProducts shift, coding standards change, companies move on. The context in which old code is reviewed will be different than the context in which it was written. Basic facts of business that needed no explanation become legacy details and historical quirks.
Comments can lead the way into dense code routines, outline tried-and-failed attempts, and warn against unexpected pain points. They can give clues about what went wrong. They might not be necessary and they might not be true.
But they just might be a gift to future.Comments are an insurance policyYes, there is a price to pay for introducing noise, ambiguity, and possible lies in your code. But theres also a cost to your home or car insurance policy.
We can mitigate the costs of comments by:Being mindful of bad practices (lazy comments and sloppy code)Being cautious about lies (trust no one)Managing the noise (using the tools in any decent IDE)The ultimate question is simple. Is the cost of comments worth paying? Opinions differ, but if youre using comments thoughtfully and judiciously if youre using them to reduce the cognitive load of code and never to counterbalance bad practices they can add value to even the cleanest code.
Heres a completely unscientific poll of the people whove read this article. Weigh in by picking the statement that has the strongest pull on your coder heart!For a once-a-month email with our best tech stories, why not subscribe to the Young Coder newsletter?