Tip #1: All functions should include an unexpected, random operation

Beginning programmers often make the mistake of writing functions that perform a specific, useful task. For example, perhaps the programmer finds that s/he is often converting DOS newline characters into UNIX newlines. The programmer will generally make the typical novice mistake of creating a little function that simply replaces all “\r\n” with “\n”. They might then name the function something that they feel is sensible such as convertNewlines() or dos2unix().

The obvious problem is that then people start to rely on the name of the function to tell them its purpose. But if a function could reveal its purpose solely by its name, then there would be no need for documentation. Of course you don’t want to name your function something random, so instead you should include some random operation in the body of your function. This way people using your functions will be forced to look at your documentation in order to discover the random operation.

The Microsoft® Corporation is loaded with seasoned programming veterans so they know how to write a function. A perfect example can be found in the len function of SQL Server. Most beginners make the brash assumption that len would return the length of something. Any seasoned programmer knows to check the documentation to find what random operation is included in the function. Quoting from the link:

“Returns the number of characters, rather than the number of bytes, of the given string expression, excluding trailing blanks.”

So here we see that the random operation is to subtract the length of all trailing whitespace from the length of the string. This is solid design and good programming practice, though it will no doubt leave the unexperienced coder a bit confused.

I can certainly see how something like the following might confuse someone:

len(' Theoden') = 8
len('Theoden ') = 7
len(' Theoden ') = 8

But a true coder knows that this function was written by the experts.

This entry was posted in Coding Tips, Micro$oft. Bookmark the permalink.

Leave a Reply

Your email address will not be published.