Cleaning up – Comment out old code

If you’ve spent any appreciable time in the programming world, you’ve probably reorganized your code any number of times. When I’m writing code, I usually slap things out as I think of them, resulting in code that (while easy enough to read) defies the principle of unity. You’ll see me write things like this:

int main()
    int i, j, k=0;

    char * message = "Says something\n";


        printf("%s", message);
    char * pandamonium = NULL;


    struct a_structure * thisone = (struct a_structure *) malloc(sizeof(struct a_structure);


You see my point. While there’s nothing functionally wrong with this code, we usually want to put all of our variables up top in one “data” section. This is something of a holdover from assembly languages (which have distinct sections for data and code), but it’s not a bad practice at all. Generally, we try to keep this standard.

Reorganizing these things, though, often introduces a number of errors. They can be a hair unpredictable – I recently dealt with a reorg that invariably threw SEG_FAULTs, even though the code appears functionally equivalent to the original.

There’s one way to ensure that you always have code that works, even as you reorganize it:

Comment the old code out instead of deleting it.

It’s a simple process:

  1. Copy your code out, so now you have two identical copies of the same blocks.
  2. Use either block comments or precompiler comments (I use #if 0 … #endif, but /*…*/ works just as well) to isolate one of those working pieces
  3. Rearrange the un-commented code, and test relatively often.
  4. If you can’t figure out why the reorg is broken, at least you don’t have to rewrite the function.

When you’re 100% happy with your reorg, you can delete the commented-out code, but until then the cost of duplicate code is too low to consider against the cost of rewrites.

Facebook Auto Publish Powered By :