

The //* /*/ //*/ comment toggle trick - creaktive
https://coderwall.com/p/zbc2zw

======
diego_moita
DON'T DO THIS!

When your code base grows you will end with dozens of places to change your
code, all of them error prone. More things you need to keep control means more
potential problems.

There are 2 alternatives to this. For languages that have macros (C#, C, C++)
use the #ifdef construct, as others suggested here. For languages that don't
have them (Java, Perl) use a less error prone alternative:

static boolean Test = false; // Only one place to change code

...

if(Test) doTest();

The difference in this last technique is that since you have just one place to
change code there is less chance for errors and the change is easier to
automate.

~~~
richardwhiuk
You should not have commented out code checked in. Period. Whether you are
doing if(0), #ifdef 0, #if 0 it doesn't matter. It makes the code harder to
read and debug (suddenly whoever comes after you can't read the whole function
/ context on the screen at once).

If you DO want to do this either:

a) delete the code. It'll be in version control anyway right? You do do
version control right?

b) put it under a NAMED feature flag. Test is not a suitable name. Put it in a
separate file which is conditionally compiled into the build with #ifdef
SHINY_FEATURE shiny_feature(); #endif

~~~
kragen
Almost all of the time I agree. But sometimes code is the clearest and most
understandable way to describe an algorithm, and sometimes you want to
describe an algorithm for a reason other than that you want it to execute. For
example, you might want to say "This would be simpler but it fails when x is
denormalized," or you might want to say "This is how you could call this
method," which is common in Python and elisp docstrings — and, I think, wholly
defensible in that case.

~~~
3pt14159
Most days I don't write comments. Maybe once every 3 months. When I feel like
someone might need a comment I rewrite the code until I feel like they don't
need a comment.

The only time I write comments is when:

1\. Someone fucked up big and shipped an iPad app or something that relies on
an error in the API or something. Can't force users to upgrade iPad apps,
especially on older ones who are fearful of the app breaking or getting worse,
so you end up with these massive comments fully explaining the problem, the
hack that solves it, the conditions that need to be met in order for the hack
to be solved (for example, "check google analytics to see if the number of
people using version X of the iPad app or lower is less than 1%, if it is,
replace the bellow hack with the following solution"), and possibly other
hacks investigated and the reasons that they were declined. The reason you do
this in the code rather than just in the commit message is that it protects
the message from getting watered down as people change the code. I assume that
someone is in a massive hurry when they are reading code and massive wtfs
should be explained without further investigation.

2\. When the performance of the obvious solution is terrible and the efficient
solution is complex. Especially when math is involved (for example, the core
match method of a distributed recommendation engine).

------
voyou
"This trick below can be used to toggle between two sets of code, with one
symbol in the code with no additional short-keys to learn, and no tool
dependencies!"

So can #ifdef TEST / #ifndef TEST , which also has the advantage of not being
horrific.

~~~
pygy_
Cue in Java, Javascript and PHP, which don't have preprocessor directives.

~~~
aidenn0
Unless you run them through a preprocessor (which I recommend)

------
akamaka
Why are there so many angry comments on this thread?

I use this sort of trick all of the time when debugging, but I rarely commit
any commented out code as a matter of principle.

Nobody was suggesting using this for "ghetto source control" or that this is
an alternative to compiler directives.

Can't we just be polite and say "Cool hack, but obviously don't commit this
type of code", instead of getting out the pitchforks?

~~~
laurentoget
You and I may know this should never be committed. Hundreds of students and
junior developers will read this post and need to be warned that this is a
VERY BAD IDEA.

I would rather make angry comments here than to have to explain why this is a
terrible idea in a code review of an intern or a junior colleague.

------
snorkel
Yikes. At least give the next coder that will maintain your code (and perhaps
your future-self) a chance at understanding it. If the goal is to switch
between prod and test code by flipping one char, then this works, too

    
    
       if (1) 
         productionStuff();
       else 
         testStuff();

~~~
jedbrown
Yes, and this way the inactive code is still checked for validity and does not
leave -Wunused-* warnings. Use `#if 0` if you want to disable code that is
intentionally invalid, then grep your codebase for `#if 0` and delete those
dead code blocks with extreme prejudice.

------
vowelless
This should not be used. I would reject the code review if this came by me and
recommend using ifdefs.

Compilers are not uniform in their interpretation of nested comments.

~~~
qompiler
I'm going slightly off-topic here, but I have to rant a bit on code reviews.

For the love of god, please, they are meant for checking each others code for
mistakes and not for miniscule details like this. I have seen it time and time
again in various companies where code review is used as some sort of tool to
dictate style and preferences to each other. Wasting valuable development time
and creating a unhealthy tension between developers.

~~~
lotsofcows
Ironically, that's the exact opposite to the way it works in my company.

We use various automated techniques to pick up mistakes and use code review to
ensure style is consistent.

Everyone in the company should be able to parse any piece of code without
individual styles disrupting that.

The only tension occurs around the weighty question of line length - coding
standard says 76 chars max, I say that's what the IDE's for.

~~~
SoftwareMaven
I think 76 characters is a good ideal to strive for because it means the code
is legible _everywhere_ , including my phone. It also reduces variables named
request_response_header_validating_auditor.

However, some things don't break well, so readability ought to trump.

------
user24
Better way:

    
    
        /**
        testCode(); testCode();
        /**/
    

(...)

    
    
        /**/
        productionCode(); productionCode();
        /**/
    

I think this is better because it's much easier to see what you're supposed to
do in order to switch the block on or off, and it's only a single character
change per block. (though you can't switch from test to production in one
character, but meh).

However, I tend to see commented code as ugly cruft. To me, comments are for
explaining in natural language what you're doing, not for deactivating bits of
code. If it's bad get rid of it, if it's good keep it. Why comment code?

The only time I comment out code is to warn developers away from doing
something which is obvious but a bad idea, for example:

    
    
        /*
        // This was a neat idea but it makes it break if the user isn't logged in
        userPreference = getPrefFromUserSession();
        */

~~~
scott_w
I think a better way of doing that is to create a test that fails in exactly
that condition.

You can then put documentation in that test, as that's what the developer will
look at first. You also get the bonus that, if someone finds a way to fix the
function that causes that, then you can go back to possibly nicer code.

~~~
user24
That assumes TDD, but yes that would be a nice way of doing it.

~~~
Evbn
Reading tests is not TDD, it is basic due diligene when learning code. Eve
still, skipping that, when the test fails, the rush coder will see the
problem.

------
wldlyinaccurate
No, no, no, no, no! This is a terrible idea, and will end up causing you a
massive headache in the long-run. If I see commented-out code like this, I
will delete it because _that's what version control is for_.

If you _really_ need to turn code on/off in different environments, you should
be using feature flags: <http://code.flickr.net/2009/12/02/flipping-out/> and
at the very least you should be detecting the environment:

    
    
        if (ENV == 'dev')
            testStuff();
        else
            productionStuff();
    

This is much more meaningful to other developers (and to yourself in the
future).

------
coherentpony
This will compile to different things depending on whether you are using a C
or a C++ compiler. Worse, it may compile to different things depending on
which standard you compile to. If you don't want you colleagues to hate you,
you should probably use:

    
    
        #ifdef DEBUG
        testCode();
        #else
        productionCode();
        #endif
    

Or, better yet, if it really is test code then write a test.

~~~
shubb
I don't understand why someone would do this nested comments thing. This is
what macro block are for...

And tests need to be separated from the code. Hopefully using a test
framework.

If your code changes depending on if it is in 'test mode' or not (which is
what is proposed), then the test code is not the same as the production code,
i.e. the production code is not tested. I'm not just talking about timing
issues - extra variable names and objects will be in scope in 'test mode', and
might logically change the behavior of the program.

~~~
alexanderbrevig
* not all languages have macros * you don't use test frameworks for enabling and disabling code inline while you're developing

Please read the protip, understand my intention (keyword TRICK) and have a
delightful cup of coffee. You've earned it.

~~~
B-Con
Welcome to Hacker News. :-)

> understand my intention

We don't do that here. However, we do have an unparalleled menu of pedantic
critique, edge case obsession, and a wonderful sauce made from insanely
perfect standards.

------
pbreynolds
Yikes at those extra slashes. I've always preferred this way:

    
    
       /**/
       block one
       /*/
       block two
       /**/
    

Simply add or remove the second slash to toggle.

~~~
Twisol
I came up with this way when I started programming (and apparently had the
gall to assume nobody else had done this...):

    
    
          /*/
          test
          /*/
          test
          //*/
    

Just add or remove the first asterisk.

------
yuvadam
Cool trick. But there is _no_ reason whatsoever to prefer this to a simple:

    
    
        git co branch
    

Sorry. I've been burned one too may times from source-control-by-commenting-
out.

------
gordaco
I use this "trick" a lot, but I'll never ever dare committing it; just for
small and quick checks (of the "what if I use this other implementation for
the loop?"). If I'm going to commit, if (1) or #if (1) (plus a small comment
explaining why I resort to that) are better options and immediately
understandable for any other team member.

------
peterkelly
Dijkstra is rolling in his grave right now

------
alexanderbrevig
I understand the criticism, it's not supposed to be _the_ way to toggle code
in and out.

It's a TRICK, and that's all it will ever be.

However, it is the only way I know of that is not language specific for a
particular dialect of C (#ifdef) that enables code to _not_ become a part of
the compiled binary, or in JS terms - not available from the runtime.

Best regards -OP

------
HardyLeung
As a long-time C++ developer I wish people don't use any commenting tricks
such as this, and I wish people don't use /* * / to comment their code, even
if you develop in C. Instead, use // in modern C/C++.

The reason is that we often need to comment _OUT_ code during development. In
C++, the 4 choices are: (1) #ifdef, (2) bool dothis = false; if (dothis) { ...
}, (3) /* * /, (4) // ...

Among them, I would say the best and least-confusing way to comment out a
block of code is /* * /. #ifdef's are very confusing especially if you have
multiple of them; // needs to be applied to every line so only works in small
scale; if (dothis) doesn't work across multiple functions, and at a glance it
is harder to discern whether this is a "comment-out", or a legit condition.

However, by using /* * / in your comments, you eliminate the possibility of
commenting out blocks of code that contains /* * / comments. The problem, of
course, is due to how the opening and closing symbols are matched.

~~~
mzs
I've adopted:

#if 0 /* reason _/

lines of messy stuff ...

#endif /_ reason */

That short comment makes it easy for me to find the ends.

~~~
mzs
Ha, I thought I put in the asterix-esses. You know what I mean, but I bet cpp
actually ignores e everything after #if 0 and #endif, don't do that please ;)

------
noptic
This is a nice trick for quick comparison and thats it.

I actually use this a lot for performance comparison. This way it is easy to
toggle between the olt d and the new implementation and see how long it takes
to run the code 1000 time in javascript.

But I think anyone who check ins something likes this should be slaped.

~~~
alexanderbrevig
This is exactly what this trick can be used for. Thank you for voicing your
opinion. Happy coding!

------
AshleysBrain
This is a pretty cool trick, and I like that they shared it, but I don't think
it's better than #ifdef!

------
rplnt
Slightly relevant.. in an introductory C ourse at my university, we had to
write a program that would tell us which version of the standard was used by
the compiler. I can't think of a solution now but I'm sure it was based on
different comment syntax.

------
epo
This is ingenious but if used in a work environment should result in instant
dismissal.

~~~
recursive
You know you can use something for debugging without committing, right?

------
ryanthejuggler
I've been using this for a while in my JS projects. I'm about to start my
first job as a web developer for a medium-sized company so I'm glad I came
here and read all the backlash to this technique!

------
clearly
This is terrifying!

~~~
delinka
Care to elucidate?

~~~
majelix
It's a fairly subtle way to dramatically change the behavior of your code.
Frankly, it's a timebomb threatening to run testCode() in your production
site.

The low cost makes it useful for quick development, sure, but for stability's
and sanity's sake, please remove when you start promoting this above your own
playground.

------
huhtenberg
Everyone with a syntax highlighting editor discovers this trick sooner or
later. Why spoil the fun of the discovery and post the solution? :)

------
sriram_malhar
Cute trick, and lovely addition to the Obfuscated C code contest. Not for code
to be used by anyone else (or by yourself after a few months).

Reminds me of another trick for debugging C++ programs. This allows you to
dump data structures easily:

    
    
        #define private public
        include <foo.h>

------
mikeash
If you actually commit this code to a repository I later encounter, I _will_
find you.

~~~
Evbn
And since OP doesn't know how source control worms, he will never know how you
found him.

~~~
alexanderbrevig
You're the one not knowing how to read and comprehend. This is a trick, I hope
you learn some some day. My god this is tiring...

------
lambda
Why would you do this instead of #if 0/#if 1? Has exactly the same effect, is
a one character toggle (sure, it's editing one character rather than
inserting/removing one character), and is much easier to read and remember.

------
vorg
This trick only works if there isn't a * / inside a string in commented out
code (or there isn't a * / within the commented-out code itself in a language
that allows such syntax, e.g. GrOOvy).

~~~
Evbn
Sad that the completely obvious fatal flaw in the entire premise is so far
down the page here.

------
wting
Rather than relying on syntax tricks, I'm sure most editors allow for block
commenting or comment inversion.

For example with NERD Commentor vim plugin, you can toggle block comments with
`<leader>c<space>`. Inverting comments is `<leader>ci`.

<https://github.com/scrooloose/nerdcommenter>

------
JoshTriplett
Fun related trick:

    
    
        $ cat test.c
        int compiler_supports_single_line_comments = 1 //*
        //*/ 2
        ;
    
        int main(void)
        {
            return compiler_supports_single_line_comments;
        }
    
        $ gcc test.c -o test && ./test ; echo $?
        1
        $ gcc -std=c89 test.c -o test && ./test ; echo $?
        0

------
shin_lao
Why don't you use macros?

Additionally, source control tools make deleting code much more convenient,
no?

~~~
delinka
During debugging, there's often the need to temporarily disable a few lines of
code to see the effect it has. I'm certainly not going back-and-forth with
source control for something so trivial.

That said, macros do make sense in this case- you can #define a single flag
(e.g. FLAG) as a 0 or 1 and simply #if FLAG ... #endif, but it's certainly
more typing to set up.

~~~
shin_lao
In that case I think I would prefer to use my editor's keyboard shortcut to
comment out code, but that's a personal choice.

------
dbbolton
A much more elegant solution is to use Commentary[1] in Vim (and I'm sure
there's an emacs equivalent too). Just use visual mode to select your text,
hit `gc`, and voilà.

1\. <https://github.com/tpope/vim-commentary>

------
DalekBaldwin
In Python:

    
    
      #'''
      some_code()
      '''
      some_other_code()
      #'''
    

... with one character toggled, becomes:

    
    
      '''
      some_code()
      '''
      some_other_code()
      #'''
    

If you work with anyone who says "Don't do this," don't do this.

------
NotDaveLane
Dependency injection[1] would be preferable. Alter behavior based on defined
environments (dev, test, staging, production), not whimsy.

[1] <http://en.wikipedia.org/wiki/Dependency_injection>

------
qompiler
In Eclipse you can hit CTRL+/ to comment and uncomment a block of code you
have selected.

~~~
jrabone
Or CTRL+SHIFT+C to comment and uncomment a selection using single line
comments.

Or switch to block selection mode, make a multi-row zero-column selection and
type //

I love Eclipse.

------
wglb
Let's not do this.

------
q_revert
for any vim users I would recommend having a look at NERDcommenter, from the
author of the very popular NERDtree

<https://github.com/scrooloose/nerdcommenter>

------
Twisol
There's a slightly less-interesting Lua analog as well:

    
    
        --[[
          Code block one
        --[=[ Explanatory comment here ]]
          Code block too
        --]=]

------
npsimons
This seems . . . silly. I mean, honestly, do code editors besides Emacs not
have something similar to comment-dwim?

------
huyvun
on non-gcc compilers this is valid

#define include_them 1 #if (include_them==1) #define hotcode /##/ #else
#define hotcode #endif

void func (void) { hotcode printf("if included_them true, compile this line");
}

------
lnanek2
Please just use if/else and a flag. It's much clearer and more maintainable.

------
mkadlec
I never liked this kind of code practice, makes it very difficult to read!

------
TheAnimus
Or just select the text and hit CTRL + K, C

At least in my IDE anyway.

------
lucb1e
Is it bad that I first saw this trick on NerdParadise.com?

------
benaston
tldr: Don't do this.

------
CyberDroiD
I like 'Code Opinion Blogs'. Interesting insight into what people prefer when
coding!

------
laurentoget
worse idea ever.

if you need to have branches in your code, learn how to use your source
control environment. even cvs lets you branch your source tree.

~~~
alexanderbrevig
This is not an attempt at branching, this is a trick.

The protip is not to use the trick, but to know about it. Read the tip, try to
understand the intention - then criticize. Thank you kind sir.l

