Saturday, July 23, 2011

VBScript Coding Guidelines

When you first start writing code, you have to concentrate so hard on just getting the syntax correct for the computer that it may be easy for you to forget about all the things you need to do in order to make sure your code is human friendly as well. However, attentiveness early on will pay huge dividends in the long run.

Expect the Unexpected

Always remember that anything that can happen probably will happen. The idea here is to code defensively — preparing for the unexpected. You don’t need to become totally fixated on preparing for all contingencies and remote possibilities, but you can’t ignore them either. You especially have to worry about the unexpected when receiving input from the user, from a database, or from a file.

Whenever you’re about to perform an action on something, ask yourself questions such as:

  • What could go wrong here?
  • What happens if the file is flagged read-only?
  • What happens if the file isn’t there?
  • What happens if the user doesn’t run the program from the right folder?
  • What happens if the database table doesn’t have any records?
  • What happens if the registry keys I was expecting aren’t there?
  • What happens if the user doesn’t have the proper permission to carry out the operation?
If you don’t know what might go wrong with a given operation, find out through research or trial and error. Get others to try out your code and get their feedback on how it worked for them, on their system configuration, and on their operating system. Don’t leave it up to your users to discover how well (or not) your script reacts to something unexpected.

Always Favor the Explicit over the Implicit

When you are writing code, constantly ask yourself: Is my intent clear to someone reading this code? Does the code speak for itself? Is there anything mysterious here? Are there any hidden meanings? Are the variable names too similar to be confusing? Even though something is obvious in your mind at the moment you are typing the code, it doesn’t mean it will be obvious to you six months or a year from now — or to someone else tomorrow. Always endeavor to make your code as self-documenting as possible, and where you fall short of that goal (which even the best programmers do — self-documenting code can be an elusive goal), use good comments to make things clearer.

Be wary of using too many generics in code, such as x, y, and z as variable names and Function1, Function2, and Function3 as function names. Instead, make them explicit. Use variable names such as UserName and TaxRate. When naming a variable, use a name that will make it clear what that variable is used for. Be careful using abbreviations. Don’t make variable names too short, but don’t make them too long either (10–16 characters is a good length, but ideal length is largely a matter of preference). Even though VBScript is not case-sensitive, use mixed case to make it easier to distinguish multiple words within the variable name (for example, UserName is easier to read than username).

When naming procedures, try to choose a name that describes exactly what the procedure does. If the procedure is a function that returns a value, indicate what the return value is in the function name (for example, PromptUserName). Try to use good verb–noun combinations to describe first, what action the procedure performs, and second, what the action is performed on (for example, SearchFolders, MakeUniqueRegistryKey, or LoadSettings).

Good procedure names tend to be longer than good variable names. Don’t go out of your way to make them longer, but don’t be afraid to either. Fifteen to thirty characters for a procedure name is perfectly acceptable (they can be a bit longer because you generally don’t type them nearly as much). If you are having trouble giving your procedure a good name, that might be an indication that the procedure is not narrow enough — a good procedure does one thing, and does it well.

That said, if you are writing scripts for web pages to be downloaded to a user’s browser, it is sometimes necessary to use shorter variable and procedure names. Longer names mean larger files to download. Even if you sacrifice some readability to make the file smaller, you can still take time to create descriptive names. With web scripts, however, you may encounter instances where you don’t want the code to be clear and easy to understand (at least for others).

Modularize Your Code into Procedures, Modules, Classes, and Components

As you write code, you should constantly evaluate whether any given code block would be better if you moved it to its own function or sub procedure:
  • Is the code rather complex? If so, break it into procedures.
  • Are you using many Ands and Ors in an If...End If statement? Consider moving the evaluation to its own procedure.
  • Are you writing a block of code that you think you might need again in some other part of the script, or in another script? Move it to its own procedure.
  • Are you writing some code that you think someone else might find useful? Move it.
This isn’t a science and there are no hard and fast rules for code — after all, only you know what you want it to do. Only you know if parts are going to be reused later. Only you know how complex something will turn out. However, always keep an eye out for possible modularization.

Use the “Hungarian” Variable Naming Convention

You might hear programmers (especially C++ programmers) mention this quite a bit. While this is a bit out of scope of this introductory discussion, it is still worth mentioning nonetheless. The Hungarian naming convention involves giving variable names a prefix that indicates what the scope and data type of the variable are intended to be. So as not to confuse matters, the Hungarian convention was not used in this chapter, but you will find that most programmers prefer this convention. Properly used, it makes your programs much clearer and easier to write and read.

Don’t Use One Variable for More Than One Job

This is a big no-no and a common mistake of both beginner and experienced programmers alike (but the fact that experienced programmers might have a bad habit does not make it any less bad). Each variable in your script should have just one purpose.

It might be very tempting to just declare a bunch of generic variables with fuzzy names at the beginning of your script, and then use them for multiple purposes throughout your script — but don’t do it. This is one of the best ways to introduce very strange, hard to track down bugs into your scripts. Giving a variable a good name that clearly defines its purpose will help prevent you from using it for multiple purposes. The moral here is that while reusing variables might seem like a total time saver, it isn’t and can lead to hours of frustration and wasted time looking for the problem.

Always Lay Out Your Code Properly

Always remember that good code layout adds greatly to readability later. Don’t be tempted to save time early on by writing messy, hard to follow code because as sure as day turns to night, you will suffer if you do.

Without reading a single word, you should be able to look at the indentations of the lines to see which ones are subordinate to others. Keep related code together by keeping them on consecutive lines. Also, don’t be frightened of white space in your code. Separate blocks of unrelated code by putting a blank line between them. Even though the script engine will let you, avoid putting multiple statements on the same line. Also, remember to use the line continuation character (_) to break long lines into multiple shorter lines.

The importance of a clean layout that visually suggests the logic of the underlying code cannot be overemphasized.

Use Comments to Make Your Code More Clear and Readable, but Don’t Overuse Them

When writing code, strive to make it as self-documenting as possible. You can do this by following the guidelines set out earlier. However, self-documenting code is hard to achieve and no one is capable of 100% self-documenting code. Everyone writes code that can benefit from a few little scribbles to serve as reminders in the margins. The coding equivalents of these scribbles are comments. But how can you tell a good comment from a bad comment?

Generally speaking, a good comment operates at the level of intent. A good comment answers the questions:
  • Where does this code block fit in with the overall script?
  • Why did the programmer write this code?
The answers to these questions fill in the blanks that can never be filled by even the best, most pedantic self-documenting code. Good comments are also generally “paragraph-level” comments. Your code should be clear enough that you do not need a comment for each and every line of code it contains, but a comment that quickly and clearly describes the purpose for a block of code allows a reader to scan through the comments rather than reading every line of code. The idea is to keep the person who might be reading your code from having to pore over every line to try and figure out why the code exists. Commenting every line (as you probably noticed with the earlier examples) makes the code hard to follow and breaks up the flow too much.

Bad comments are generally redundant comments, meaning they repeat what the code itself already tells you. Try to make your code as clear as possible so that you don’t need to repeat yourself with comments. Redundant comments tend to add clutter and do more harm than good. Reading the code tells you the how; reading the comments should tell you the why.

Have questions on this article? Feel free to ask me in the comments section below.

If you like this post, I would suggest you to subscribe my RSS feed to have future articles delivered to your email address directly.