TrueJournals

Tag: refactoring

If you’re writing C++, write C++!

by on May.06, 2014, under programming

Today, I came across some C++ that looked something like this:

std::string output = someFunctionCall();
if(strlen(output.c_str()) > OUTPUT_LIMIT) {
    // Trim output
}

Now… I get it. C++ is not an easy language.  C++ can be especially difficult if you’re coming from C and you’re not used to object-oriented programming, or if you already know how to do what you want in C.  But please, use the right tool for the job.

The code I came across wasn’t quite this simple (the string did not come from directly above the if statement, but the if statement is exactly the same, differing only in variable names).  I’m guessing that, at some point, this code was written in C before the project moved to C++.  However — someone, somewhere, at some point came across this if statement when refactoring, and decided that the right thing to do was to keep the “strlen” call and keep using C-style strings.

That means this person didn’t think “I wonder how I get the length of a string in C++”.  The person who refactored this line of code did not care what the intention was — they just cared to replicate EXACTLY what it was doing.

To make matters worse, someone decided that “output” should use NULL characters as a field delimiter of sorts.  I’m guessing that, in the original C code, these delimiters were properly removed.  However, this did not happen in the C++ refactor.  There was a NULL character about 20 characters into output, which meant that the call to strlen would always return 20.  It’s nice that C++ strings allow NULL characters — it’s bad when you then try to treat them as C strings.

Now, I won’t comment on the validity of using NULL characters as a field delimiter (it’s a bad idea… please, just don’t do it), but whoever decided that this line of code should not behave in the same way but instead execute the same calculation was just wrong.

Refactoring code is hard (especially if you didn’t write it yourself).  Programming is hard.  But, please, if you’re modifying someone else’s code, try to understand the intention of the code more than just the literal function calls.  The author of the original code clearly meant to execute the trimming code if the length of “output” was greater than the limit, and output.size() is the best way to check for that.

Leave a Comment :, , more...

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit our friends!

A few highly recommended friends...