40

Throughout the course of programming, you will end up with some comments that explain code and some comments that are removing code:

// A concise description 
const a = Boolean(obj);
//b = false;

Is there a good method to quickly parse which is which?

I've played around with using 3 /'s and /** */ for descriptive comments.

I've also used a VSCode plugin to highlight //TODO: and //FIXME:

2
  • 2
    As a note, /// and /** ... */ comments are also used by some documentation generators, such as Doxygen or JSDoc. If you use them or similar tools, you may not be able to use that kind of comment for descriptive comments that aren't intended to be part of the documentation. Jul 8, 2019 at 18:22
  • 1
    In javascript most lines of code will probably end with a semicolon. Unless your comments do to, that seems pretty simple, and you can write a script to check for that easily too;
    – Miriam
    Jul 8, 2019 at 19:03

9 Answers 9

191

There is a very simple solution to this: remove the commented-out code.

Really, there are only two good reasons to comment out code: to test something/make a fix, or to save code you might use later. If you're testing or fixing something, remove the commented out code as soon as you're done with the test or fix. If you're saving code you might use later, make it first-class code and put it somewhere such as a library where it can be put to good use.

19
  • 108
    Also, if the code has been checked in: just remove it. If you ever need it back, source control has got you covered
    – marstato
    Jul 5, 2019 at 17:50
  • 38
    When code is removed nobody notices it ever existed. That makes it harder to recover. There is value in leaving commented code, especially if it seems likely that it will be used in the future.
    – usr
    Jul 6, 2019 at 8:37
  • 76
    @usr: When code is removed nobody notices it ever existed - and to my experience, in 99% of all real-world cases that is the right thing. In 1%, there may be some value in the outcommented lines, however, if commented-out code stays in for several weeks or months (or longer), chances are high it won't even compile any more due to refactorings of the active code lines. The "pontential value for future uses" argument is often used as a wrong excuse by people who have an emotional problem of stripping things out of the codebase for which they had invested some hours of brainwork.
    – Doc Brown
    Jul 6, 2019 at 9:26
  • 21
    I never commit commented code without additional explanatory comments. There are rare situations where you might want the code back in the near term, but every single one of those is exceptional and requires an explanation for future developers (or future you). 90% of my comments are "Removed because it appears to be unused. Delete after Nov 2021 if there are no problems" Jul 6, 2019 at 11:58
  • 31
    My colleague once put "There was code here that did X but I removed it" when we removed some feature for the time being. That worked really well; you knew it was in source history for that file, but it wasn't bothering you.
    – Erik
    Jul 6, 2019 at 20:36
45

Adding to @RobertHarvey's excellent answer I believe there is only one legitimate reason I've ever encountered for saving commented code to source control, even temporarily: in case of non-obvious replacement code which should not or cannot be used right now for some reason. Even then most of the comment should be the explanation, not the replacement code. This could be a bug or a feature of the language which is not yet considered stable. It might look something like this:

# TODO: Replace with `foo = frobnicate(bar)` once <link.to/bug> is fixed
foo = [some complex workaround]

In this case, the work has already been done, but you can't yet take advantage of it, so deleting it means someone would have to rediscover it later. The same goes for suboptimal solutions which may seem superior on the face of it or conscious trade-offs against similar solutions.

Caution: Don't litter your code with alternative solutions. Every task can be done in infinitely many different ways, and it's not cost-effective to explore this space for a long time for every change. Code reviews can be a good place to discover such missing comments, when your colleague suggests an improvement which you have already discovered to be suboptimal.

2
  • 2
    The flip side of this is that sometimes you need to explain why you aren't using frobnicate(bar), so that no one will come along and try to "fix" your "inelegant" code. So you show them that you know that in a perfect world, the frobnicate function would be the way to go, but you know from painful experience it doesn't work correctly. There may be no expectation whatsoever that the third party even considers it a bug, much less worth fixing; you still need to leave a comment to future programmers (including yourself) about why you didn't take the obvious approach. Jul 8, 2019 at 17:57
  • 3
    A related situation is that there may be two ways of doing something, one of which will process valid data much faster than the other, and one of which will offer more useful diagnostics if, for whatever reason, it receives invalid data. If the program is part of a process that should only feed it data which is "guaranteed" to be valid, but something in the process isn't working properly, having available a version which is slower, but offers better diagnostics, can make it much easier to determine what's going wrong.
    – supercat
    Jul 8, 2019 at 19:32
20

Hmm, I read this question slightly differently from Robert who correctly asserts that commented out code should be removed.

If, however, you are looking for a convention to mark code for later removal, an old favorite of mine is:

//b = false; //TODO: remove

Some IDE's flag //TODO: comments or can be taught to. If not, it's usually a searchable string. It's best to follow whatever convention your shop has established because this can be done several ways. Every code base should do this one way. Keeps it searchable.

quickly parse which is which?

Without that mark the automated way to do this is with the compiler. If stripping the comment off produces code that compiles, it must have been commented code. Writing an IDE plugin that checks that wouldn't be hard. But it will leave buggy commented code behind.

This is why it's better to simply mark commented out code as code the moment you comment it out. This lets you work non-destructively while you decide if you really want it gone. Since we all get interrupted, and are somewhat forgetful, don't be surprised if some lines get checked in while in that state. If they do it's nice that they're at least clearly marked and searchable. Keyboard macros have helped me with this in the past. It's hard to get interrupted in the middle of this if you can do it with a single keystroke.

You can take this as far as enshrining the mark in your continuous integration tests. Oops, I'm trying to check in with outstanding TODO's again.

4
  • Instead of seeing if comments compile to label them as code, you could run comments through a natural language processor and label the ones that parse as a sentence or noun phrase in the language your team speaks.
    – TheHans255
    Jul 6, 2019 at 20:50
  • 3
    @TheHansinator that sounds good but my experience with my cellphones auto correct relationship with my coder jargon makes me cautious. Jul 6, 2019 at 23:30
  • I imagine that the NLP used to parse code comments would be a lot better than the NLP that powers autocorrect, simply because the computer has the entire sentence to work with and isn't trying to correct spelling errors. Not to mention that the false negative is better here, too - as long as a human is able to review the comment before deletion, they can just rewrite the comment, as opposed to not being alerted to useless gobbledygook.
    – TheHans255
    Jul 7, 2019 at 2:31
  • 3
    w.r.t parsing: double buffer (flip on) -> C prototype or ultra-terse English? can't tell without context, not a correct whole construct in either language. Some false positives and negatives are inevitable, when comments by their nature don't constrain the form of their content in either direction. Jul 7, 2019 at 10:06
8

I use preprocessor directives to remove code, not comments at all:

//comment
active_code();
#if FALSE
inactive_code();
#endif

This makes a very easy thing to search for, and my syntax highlighter treats it as a comment. I can even collapse it into a single line: #if FALSE(...)

You can expand on that idea to have several options:

#if OPTION == 0
code_for_option_0();
#elif OPTION == 1
code_for_option_1();
#else
code_for_all_other_options();
#endif

And compile-time error-checking:

#if FOO >= 5
#error FOO should be less than 5!
#endif

Of course, you don't want to go overboard on this, or it becomes difficult to tell what's actually getting compiled and what isn't. But you get the idea, and it's the same problem as for commented code anyway...as long as you only use it statically. If your conditions are dynamic, it's worse.


To determine which is which in an existing codebase that didn't consider this problem at all, I don't think there is a universal solution. You'll have to find patterns yourself and probably code a regex to find them.

5
  • What in the world would this be good for? Do you need to compile multiple versions?
    – Tvde1
    Jul 8, 2019 at 5:15
  • @Tvde1 That's one possibility, and a potential nightmare if you don't manage it really well. But the alternative is possibly worse. If you have multiple copies of almost the same code, one for each variation on a common theme, then you have to maintain them separately and keep them in sync.
    – AaronD
    Jul 8, 2019 at 5:53
  • There are several ways to do this, but they all have some variation of either the complex configuration problem or the independent copy problem: Are you sure that a bugfix got to all of the independent copies? What if not, and another feature gets added, that is then broken by the bugfix that was known before the feature but not ported until now?
    – AaronD
    Jul 8, 2019 at 5:53
  • 3
    That only works if you have a pre-processing step like C. The question is about javascript. You could do some pre-processing but it's going to stretch the build system's capabilities and it's also non-standard. If you don't have a build system or the build system doesn't at all support parsing and executing code, you will not be able to implement this solution. Finally, it doesn't even address the question - commented out code is not strictly equivalent to code that is conditionally activated. It could be a leftover that's not meant to be enabled.
    – VLAZ
    Jul 8, 2019 at 8:20
  • Conditional activation is only an extension of the answer and not the answer itself. Otherwise I would edit it to include the comments that extend it even further.
    – AaronD
    Jul 8, 2019 at 16:37
4

I agree with the answer stating that old code should be removed rather than commented out where possible, however I have observed a convention for those few occasions when commented-out code is needed.

(My basis is C# but this can be applied to any C-syntax language eg java)

// An explanatory comment has a space between the comment marker and the content.

// The following lines are commented out code so do not have the space (except where indented).
//var a = something();
//if(a==2) {
//   doSomethingElse();
//}
2
  • 2
    This depends totally on style: When I comment out code, I generally add the // to the first column, and since virtually all code is indented, the result is virtually always that the comment starts with some tabs. Normal comments don't get a leading space from me, unless there are already other comments with a leading space in the vicinity. So, your method would fail abysmally on comments that I produced, and any method designed to recognize my comment patterns would fail abysmally on yours. Jul 6, 2019 at 17:01
  • @cmaster Ah I see, I think I misunderstood the question. I provided a simple way of formatting the comments in such a way that they can be easily parsed for type, which isn't what was asked for.
    – IanF1
    Jul 6, 2019 at 18:09
3

I am interpreting the question different still, thinking you want to find commented out code.

C-style code is bound to have semi-colons in it while comment is unlikely to have semi-colons in it. So for single line commented-out code you could use this regular expression:

\s*\/\/[\s\S]*;

For multi-line commented-out code it could be

\/\*[^\;]*;[^\;]*\*\/

Note Visual Studio is a bit peculiar about line breaks in regular expressions, they do not count as whitespace, you need to specify an explicit \n.

1
2

If you use an editor with a compiler running in the background (like Xcode and Clang), you can just try to compile the text of the comment. For example”a concise description” gives errors, “b = false;” doesn’t. You could then use different syntax highlighting.

A simpler method would be an IDE plugin that uses some heuristics, like multiple words in a row other than keywords points to comments, matched curly braced point to code etc.

1

Other answers have covered variations on the "don't comment out code" theme. But sometimes you do still want it around for reference.

If you genuinely need the code to stay around, a better solution is to surround the code with "#if 0 ... #endif", ideally with a comment to say why. This is the recommended strategy from various coding standards, including MISRA.

-3

Simple, at least for me - and in C/C++. Comments enclosed in /* */ are informative. Test code that is temporarily removed is commented out with leading //.

And there is good reason to leave test code in the file but commented out, at least in the sort of work I do. Sooner or later someone will want a change made, which will need that code. Uncommenting a block takes one editor command, as does re-commenting it where you're finished.

11
  • There's also #ifdef __DEBUG ... #endif, or whatever custom definition you want to use. __DEBUG is nice though, because you often only have to change the project configuration to get it. But most IDE's let you define your own configurations as well, which can give you anything in that spot.
    – AaronD
    Jul 8, 2019 at 6:12
  • What do you mean by “test code”? Unit tests? Those shouldn't be commented out at all but kept in the test suite and run as often as possible, regardless of whether somebody thinks it's necessary. Sure, it's easy to re-un-comment a piece of code, but it's even easier not not do anything at all and have the test suite already in place doing it... Jul 8, 2019 at 12:27
  • 1
    Argh, don't do that. Commenting out code "to test something" will work perfectly fine 99 out of 100 times... and in the single case you'll forget to remove it (if it is no longer needed) or - even worse - forget to uncomment it (if it is needed) and things may get ugly.
    – CharonX
    Jul 8, 2019 at 14:31
  • @leftaroundabout: No, I mean things like printf statements put in to check values.
    – jamesqf
    Jul 8, 2019 at 16:27
  • @jamesqf you should never need that kind of stuff, that's what a debugger is there for. But even if you use printf / cout or similar for getting newly-written code right (which I'll admit I have done myself in the past), it's really not very effective to leave them there. If somebody want to make changes and knows which variables they need info about, it's quick and easy to write the printfs anew, whereas if that dev doesn't know what's needed and just un-comments all those printf statements then the huge swath of text in the terminal likely won't help them either. Jul 8, 2019 at 20:10

Not the answer you're looking for? Browse other questions tagged or ask your own question.