My regular readers (both of them) may notice that my previous article basically disavowed the idea of the "code smell". The term is too often a sm...
For further actions, you may consider blocking this person and/or reporting abuse
I disagree. Comment itself is not a "code smell", its misuse is.
There are situations where leaving a comment is a necessity.
Comments are not meant to describe things, but to clarify certain statements and leave notes, regarding use of certain constructions and tools.
For example :
I disagree with the above samples. I hope I don't go too much into detail :)
On first one I'd remove the comment and write a test which would ensure correct output. If later on somebody gets an idea to remove the
value === null
because it is "not needed" the test will break and they'll see why.Second one should be
userInput % 360
. To me the comment tells what the code does (modulo) so there is no need to reiterate it, and I would remove the comment upon seeing it. It also lies because the code doesn't do anything to check against negative values, so the comment could give a false feeling of correctness. Tests would ensure correctness.For the third one I'd add emphasis that it should tell exactly which 3rd party module is in question, and also suggest a short comment on why the bug has to be worked around the way it is (especially if the code for it isn't obvious). Reason: I've seen people use these "due to bug in 3rd party..." comments as-is and they're not useful. Of course the link is the meat, but because the Internet cannot guarantee links to work forever I'd always also add the minimum necessary required for understanding into the comment.
I agree, tests will prevent things from being removed without notice, but having one line right by the function would (hopefully) prevent the "refactoring" altogether.
Good point on modulus, bad example.
It was implied that the comment would state the name of the package or in the worst case link to GitHub issue will.
Bottom line, If you're not sure if you should leave the comment - you should.
It's a text, it's a core feature of every single language and it's meant to be used, not feared.
Maybe I've had bad experiences or bad luck, but I've noticed comments to be rather ineffective against "refactoring". You need only one person with too strong an opinion and less experience who successfully ignores what the comment warns or informs about, and goes ahead changing and breaking things.
Code reviews don't perfectly protect against this as those may get through by another who doesn't stop to care about the comment, possibly because it doesn't appear in the diff. Only tests seem to successfully protect against this, at least against breaking stuff. You'd have to go for slightly malicious mindset to start removing or changing valid tests. These "refactors" are often done thinking it is an improvement, with no malicious intent.
This is one reason why I keep comments as the absolute last tool to convey understanding that the code or naming things can't provide.
I'm pretty sure that this is exactly what I described in the article.
Please forgive me if I misinterpreted your article.
It seemed to me, that your article main idea was "don't use comments unless you're absolutely sure", opposite to "use
commentscode wisely".Descriptive, long variable names can be good. However you should still be cautious with length, repetition and context.
If the file already defines context you don't need to repeat that context in each name especially if those variables are not exported.
If you have multiple variables that have repetition of the same things you may want to consider changing the names for visual clarity to make emphasis on how they are different. The more similarity there are between two variable names, and the longer they are, the harder it becomes for human mind to keep track of them.
I've seen people do things like this.
I would say
currentTotalInShoppingCart
is roughly the maximum length you should usually have for a variable name. There are OK exceptions. With this particular case I'd probably remove the wordcurrent
for quicker distinction of differences, but even that decision depends on other variables in the file.There are no absolute correct answers, but you can do your best to make the code reading process effortless.
Agreed on all fronts. As I stated in my article, I strongly prefer full-word-name variables. What I didn't explain in the article is that this often leads me to think - deeply - about the "exact", most-concise way to name a variable such that it is 1) clear, 2) descriptive, and 3) as short as possible.
It's not uncommon for me to refactor code because, when I was first writing it, I couldn't think of anything clearer than
longYellowFruit
. But later, while I'm reading the code, I realize that it's soooo much simpler to just call the variablebanana
.I also share your frustration with context that is needlessly stuffed into the variable names. One great example of this annoyance is in objects. I see stuff like this far too often:
Despite my love of descriptive names, code like this drives me nuts. There's usually no reason for the repetition of
Name
inside each of the keys.Yup, and my comment wasn't really to question anything in your article, I think it is very much on point. Went more for providing more food for thought for the others that end up here and might find this topic for the first time :)
I've always found that way of thinking very childish. Code is read way more often than typed, so choosing variable names that are shorter to type is incredibly short-sighted.
It's not that I don't often find myself thinking that. But I often find myself thinking "damn I want a siesta right now" yet I don't just start sleeping in the office.
Comments should never (unless you're hacking bits in an OS kernel or something) explain the code. They should explain design choices:
So overall I'd say I pretty much agree with the article, though I find the title somewhat clickbaity. There's so many valid uses for comments that calling them a "code smell" is really stretching the expression a lot.
This has so many underrated implications.
Guilty as charged! But I made a point to illustrate exactly where comments are useful (critical, even). And my examples pretty much line up perfectly with yours.
And with regard to those who complain about variable name lengths, I also find their arguments to frequently be arbitrary. In other words, they complain about the length of the variables you've chosen, but when they decide to use a longer naming convention, it's totally "OK".
I get the point of this and I agree largely. Comments are tools and can be used or abused.
Some things need comments. For example, in C# some absolutely amazing code can be written in (e.g.) LINQ or Rx.NET, and without the comments you might as well be looking at hieroglyphics for a while.
Come to think of it though, LINQ, Rx.NET and perhaps SQL are the only examples of where I think comments are often essential I can think of. I don't even want to think about regular expressions - I prefer to pretend those things don't even exist.
I'm not familiar with Rx.NET. But as a C# dev myself (although it's been some years since I was "in the thick of it", this is exactly why I do not like LINQ. I've seen numerous C# devs write some absolute chicken scratch in LINQ, and then swear to anyone who will listen that it's "beautiful". You don't have to agree with me, but I stand by my original contention: If I need comments to understand your (LINQ) code, then it's some crappy code.
As for SQL, no, you absolutely do NOT need comments to understand a good SQL command. Some years ago, I was working with a guy who'd never seen the way that I wrote SQL statements (which was quite different from the way that he - or anyone else - wrote them). He took one look at it, processed it for a few seconds, nodded his head, and said, "Yeah... I get this." And from there forward, he always wrote his SQL statements in the exact same format that I do.
So ah, how do you write SQL statements?
To be clear, I don't mean to imply that I have some awesome magical way of writing queries that makes the hairiest queries easy to understand for even the most junior of devs. But this is an example of how I write them:
That may not look "revolutionary", but there are a few key points to this format:
firstName
oraccessLevel
. It's always referenced asperson.firstName
orpermission.accessLevel
.SELECT
, the order is alwaysSELECT
followed byFROM
followed by any-and-allJOIN
s, followed by any-and-all filters, followed byORDER BY
(if needed).Also, I never alias them into one-or-two-letter abbreviations. I hate this:
In contrast, I often see queries written something like this, and I hate it:
If this queries tends to "grow" over time, as the dev team decides that they need to add more return values and more
JOIN
s to it, it becomes ever-more-difficult to simply read.I see what you mean. Not magical but definitely better. I use SQL infrequently but I've written queries the second way and now I'm going to write them your way. It is much clearer π.
Thanks!
I tend to over comment my code, mostly because I'll look at it and then 6 months later I will loo at it again. It always ends up that I can't remember why I did anything in the code so the comments are to remind me. This was all internal code at my employer and mostly tools not apps. In the end, I suppose you could instead write a doc, and then add issues instead of adding "FIXME:" type of comments.
I still enjoy adding lots of comments, but most of the time my code tends to be self documenting.
I definitely don't like the idea of external documentation - cuz in a quarter century of doing this, I have never seen the external documentation kept up-to-date with the live code.
Also, I don't hate the
TODO
/FIXME
type comments. I personally think they can be useful when you're in a pre-launch state and the code is changing rapidly and you want to remind yourself that you need to do a little more work at this point in the code. But once the app is launched, I've rarely ever seen those comments acted upon. They become just as stale (and as meaningful) as a bit of "Kilroy Was Here" graffiti.Oh I agree. But I've been really happy with past self for writing for for future forgetful self. In these cases I'm the only person likely to see the code so I guess it works for this particular scenario.
For FOSS projects, I try to write self documenting code, but still try to put some comments in. I'm open to knowing alternative ways to give myself hints on what I was thinking without writing a design document! :-)
Great post. I completely agree that comments should not say WHAT the code does (such comments just duplicate the code), but WHY the code is here or WHY is it written that way, HOW it is supposed to work or WHEN it is supposed to be used.
You described WHAT and WHY.
HOW - For complex problems, briefly describe the logic behind. Not the actual two or three lines, but overall concept. Imagine something more than just a = b * 1.07, where several other methods are called, etc. With proper comment, you may not need to study it deeply. Also, HOW helps with writting tests and debugging.
WHEN - Describe appropriate use case. When it should and when it shouldn't be used. Let's say that you have method that is consuming a lot of time (which may be correct behavior) and it shouldn't be called in UI thread. Of course, only add such comment when there is a possibility of misusing the method.
Good points. I could quibble that "how" can often be accomplished by writing cleaner code. But that's not always the case.
I especially agree with "when". Sometimes you open a code file and there's a function/method there that doesn't seem to be called from anywhere within that file, and you literally can't imagine when it would ever need to be called. In those times, it's tempting to consider "cleaning" it up - by removing it. But it can be extremely helpful to have a comment there that explains, "this only gets called by a cronjob that's launched nightly from the client's environment".
Back in college, I had one prof who told us to comment EVERYTHING, and would grade us on our comments.
This was also the prof who wanted us to name our variables/functions "x", "foo" or "bar".
I caused him a lot of grief when I said we needed more explanatory names and less comments. I wish I knew his contact info so I could send this too him. π
Read the article with a frown ready to point out the usefulness of comments to explain the why, then got to that section and thought: well done sir :D
(although there are other nasty code smells that are guaranteed to cause trouble; a common example I've come across is functions returning an empty array/ object synchronously that gets populated async after the return with XHR call results, relying on pass-by-reference, when the proper way would be to return a promise. This kind of shit breaks React re-rendering as the prop doesn't change)
I don't normally agree with articles like this, as I feel so much of what we do in this particular human endeavor is subjective.
I completely agree, though. I'd go one step further and say that we should document our intent. I've gone into far too much code a few years after it was written and wondered why things were done the way they were. It's risky to have code like that, you never know what is intentional, what is a bug, and what is a common-law feature.
Hi Adam,
Again, nicely written article.
I would add that using long names to explain your code should be the norm. But good naming is an art.
The team should refuse to validate functional code if there are some naming issues.
Code is not just the instructions you give to the machine. It's also the way you inform the future maintainers of your code what it does. It's your communication tool to the future YOU that will read this code two years from now.
The issue with comments is that they become obsolete when the code evolves.
And the only thing that evolves with your code is your code...so everyone should keep in mind that code that works and have no bugs is not sufficient.
You should strive to produce self documented code. And most of the time self documenting code, means long names that convey meaningfull information.
I agree with all of this. And in my article, I completely forgot to point out the tendency of comments to become stale and unrepresentative of the very code in which they're embedded. I particularly enjoy this statement:
I believe this is a common sentiment of lazy programming styles and in general, the common practice of most Javascript only programmers.
Code comments are the best way to expose an API, here's a classic example (shown below). As can be seen, this is an API for the package Restangular. Not a single comment which means, the programmer has to look up each method, read and understand what it does, rather than read what it does via the API.
A colossal waste of time which breeds false job security for those that "learned it" and put into a production system. Thinking my job is secure "just because only (we) know it" is a 1980's thing. Anyone using that model today should be immediately fired.
Today, it's about speed to delivery, any APIs that are poorly documented or have no API comments should be rejected in totality, and removed from current code.
So the real question is how do we use this piece of trash which has 'extraordinario mal olor'?
I strongly agree with the 'Why' sentiment. Sometimes apps change and our models or modules were not adequately abstracted to gracefully internalize the change. That's when comments are useful like you mention. Tell me why I'm seeing an anti-pattern in the code base not what it does.
Thanks for taking the time to offer your examples!
Yup, another third-rail topic that's sure to electrocute anyone who touches it.
Here's the counterpoint to your post: You should write a comment on every line of code.
Of course, in the end the only person who will ever read your comments is you. So write them for yourself. Or don't.
I feel like the title of this article contradicts with the point that I think you are trying to make, which is "comments when misused contribute to code smell". Correct me if I'm wrong though.
We're probably picking nits here, but my point is that:
Very great article! Thanks so much.
Great post
Very nice article with great points. Thank you :)
Here's the only truly defensive code:
github.com/v6/nothing
And I'm proud to say, it requires no comments.
Great writeup, my view exactly
if you don't have anything useful in the comments there is no use (get rid of them)
Totally agree
For APIs comments are only way to go.