Five Points for Good VBScript Style
A few basic rules can help you avoid the most common scripting mistakes.
June 1, 2010
Casual admin scripters have few worthwhile sources of advice for good scripting style. There certainly are sources, but they're generally complex, programmer-focused, and don't deal with the real-world issues for writing better scripts. The practical points for effectively working with VBScript are brief:
1. Get a good text editor.
Syntax highlighting, complex search and replace, and customizable layout all make reading and modifying code better. If that weren't so, C programmers would all use Notepad. The Cadillac of script editors is, of course, PrimalScript. If that's beyond your budget, there are good tools with prices all the way down to free - such as ScITE and PrimalPad.
2. DO NOT start scripts with On Error Resume Next
On Error Resume Next shows up in scripts everywhere, and it keeps you from finding out when and why scripts have problems. When it's ok for a specific statement to fail, put On Error Resume Next immediately before the statement. Immediately after the statement, put any code that tests error values. Follow this with On Error Goto 0 to turn error display back on.
3. DO start with Option Explicit
Starting with Option Explicit isn't to force you to use explicit declarations for each variable. It's to protect you from minor mistakes you make when you edit a script.
4. Use readable, precise, economical variable names
Complex naming schemes harm scripters more than they help. Rather than obsessing about names, pick readable, precise, economical names. A variable name should communicate what the variable is. If you're storing the path to a file in a variable, a good name is filepath—or, if you like the extra hint provided by using a prefix to identify variable content, sfilepath may work. Using filename or file implies that it's merely the file's name or a file object. Studies suggest that in the easiest-to-maintain code variable names range from about 9 to 16 characters in length, so be moderate in the length you use. In the case of objects or concepts you use regularly, short unique names are ok; workhorse technologies like WMI are highly recognizable by name.
5. Comment hacks and struggles
You need to understand what code does when you (or someone else) reads it later. Comment on the specific parts of a script that need it. If you took shortcuts to solve a problem, explain the limits. If you struggled with a concept before getting the syntax right, explain it right there so you'll grasp the idea in six months.
About the Author
You May Also Like