Patterns: Names as Documentation

While it’s usually less of a problem in C, in my Java days I saw any number of functions with names like “solve” or “act”. These functions were usually overloaded, so that “solve” meant one thing for integers and a wholly different thing for strings.

Tell me, if you were reading a piece of code and you see a line like this:

solve(a, b, c)

How would you know what that function is doing?

Meaningful names

We’ve discussed defining function and object names which employ a CLASS_OBJECT_function structure. The problem is, there’s little difference between the following Java and C:



In both of these cases, if the “function” name is just “solve”, there’s not a lot for us to go on.

Now, if we replaced the function name with something like “RSA_encrypt” or “DES_rotate”, we have something meaningful. We now know that the function is supposed to (in the examples) encrypt some input using RSA or perform the rotate operation defined in the DES standard.

Now we know exactly what the function is supposed to do, so we don’t have to go very far to determine whether it’s working properly or not.

This goes further than simple object and function naming conventions. When you instantiate a variable, you run into the same problems.

Suppose you have a set of variables with names like these:

int thing;

char *stuff;

uint8_t num;

While these may be fine in small functions (because there’s no room for confusion – you see it instantiated and employed in the same screen), they’re problematic in larger and higher-level functions.

If your main function has variables like that, you don’t know what they’re supposed to represent. However, if they have names like these:

uint64_t RSA_256_key_pub[4];

int object_expected_size;

char *error_message;

Suddenly, we have an idea of what these variables do.

Admittedly, this increases the amount of time you spend typing (and my heart bleeds for you), but it reduces confusion while you’re writing the code and makes maintenance hundreds of times easier.

Lesson: Well-named objects and functions make reading and designing code easier.

Facebook Auto Publish Powered By :