Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way to toggle commented code?

If I have two chunks of code and I want to toggle between them (say, for testing purposes), I've realized you can use a comment like this:

//*
<chunk #1, active code here>
//*/

/*
<chunk #2, commented out code here>
//*/

Then to switch between them I just need to add a / above #2 and remove a / from above #1. I know IDE's have "toggle comment" commands, but I think this is faster and less messy.

/*
<chunk #1, active code here>
//*/

//*
<chunk #2, commented out code here>
//*/

This obviously works because the line comment actually comments out the /* so the block comment isn't parsed, and same thing for the end where the // actually comments out the */.

My question is if there is a better way of doing something like this with comments, or if this method is as 'slick' as you can get with commenting?

like image 760
WOUNDEDStevenJones Avatar asked Mar 05 '26 06:03

WOUNDEDStevenJones


1 Answers

Let me start by saying that I think it's evil to use cryptic systems of slashes and asterisks to toggle code, but let's try this anyway.

First block selected

//*
public static void doStuff()
{
    System.out.println("foo");
}
/*/
public static void doStuff()
{
    System.out.println("bar");
}
//*/

Second block selected (the only change is removing the first slash):

/*
public static void doStuff()
{
    System.out.println("foo");
}
/*/
public static void doStuff()
{
    System.out.println("bar");
}
//*/

It works because of the /*/ in the middle which functions either as on open or close comment block depending on whether or not there was an already opened comment block.

It's similar to your own approach, but the advantage is you can toggle by changing only a single character instead of having to change two characters. So it's a slightly more efficient way to be evil.

like image 83
Mark Byers Avatar answered Mar 06 '26 20:03

Mark Byers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!