Friday, March 11, 2011

Don't Avoid No-ops

A form of spurious case analysis that seems to come up a lot in the code I have to work on right now falls under the category of "avoiding a no-op". Well, don't add cruft to your code just to avoid a no-op.

Here's the one that I see hundreds of:
  if (ptr != NULL) {
    delete ptr;
  }
Instead of:
  delete ptr;
But the line that caused me to post this today was this:
  if (!isalnum(str[i]) && (str[i] != '_')) str[i] = '_';
Why complicate the if condition just to make sure and not overwrite an underscore with an underscore? In reading through this code I paused to consider when an underscore could occur, and whether something special had to happen, only to read a little further and see that someone was guarding against a no-op. Good lord, just perform the no-op so I can read this more easily:
  if (!isalnum(str[i])) str[i] = '_';

No comments: