Naming Variables

Microsoft® Windows® 2000 Scripting Guide

microsoft windows 2000 scripting guide

« Previous | Next »   

If you were writing a novel, it is unlikely that you would give every character the same name. Although the storyline would not change, the plot in such a novel would be very difficult, if not downright impossible, to follow. That is at least one reason why novelists give their characters unique and sometimes very meaningful names.

In the same way, the use of unique and meaningful variable names can make your scripts much easier for others to read and understand. For example, the following script snippet includes a mathematical equation. You cannot easily tell if this equation is correct because the script uses variables named x and y. To make things even more confusing, the variable x is used not only as one of the items in the equation but also to represent the end result of the equation. This is allowed in VBScript but not recommended; reusing variables often causes confusion for people maintaining a script.

x = 2 y = 4 x = x * y 

Compare the preceding script to the following script snippet. Although the scripts perform the identical function, meaningful variable names greatly improve readability. Furthermore, each variable represents only one item. As a result, it is very easy to look at this script and verify that the equation is correct.

Length = 2 Width = 4 Area = Length * Width 

The preceding script uses variable names that clearly indicate what each variable represents. Keep in mind that even a variable with a name such as UserInfo can cause confusion because it does not indicate what kind of data should be stored in it. More descriptive names, such as UserMonthlySalary, UserIDNumber, and UserLastName, are less likely to cause confusion.

Using Hungarian Notation

It is also helpful if variable names indicate the type of data stored in the variable. Variable names such as strUserLastName indicate not only that the variable stores the user s last name but also that this name is made up of string data. This type of naming scheme is commonly referred to as Hungarian Notation.

Note

  • The term "Hungarian notation" was coined in honor of former Microsoft Distinguished Engineer Charles Simonyi, who first proposed this method of naming variables. The term was chosen both in deference to Simonyi s Hungarian nationality and to the fact that resulting variable names such as strUserLastName did not always resemble English. The Hungarian Notation used in this chapter has been slightly modified from the original version to better meet the needs of script writers.

Hungarian notation is based on the premise that the name of a variable should tell you everything you need to know about that variable. In addition to describing the purpose of the variable, variable names have a prefix that indicates the type of data that the variable holds. This is especially important with VBScript because VBScript is a typeless language: VBScript variables can hold any type of data, making it easy to inadvertently store the wrong data in a variable.

For example, by looking at the variable named UserID, you cannot tell whether a value such as ACCT-1005 is a valid ID. If UserID can contain string data, ACCT-1005 might be valid. If UserID can contain only numeric data, however, ACCT-1005 is not valid.

By adding a prefix that indicates the type of data stored in the variable, you can more easily identify problems that occur when the wrong type of data is stored in a variable. Because VBScript is a typeless language, nothing prevents you from storing an improper value in the variable. However, when you are debugging a script that is not working properly, noticing that a variable named intUserID has the value ACCT-1005 immediately provides at least one reason why the script is not working. Assigning improper data types to a variable also causes problems when dealing with databases, which typically require the correct data type, and when carrying out mathematical equations, date conversions, or other functions that require specific kinds of data.

When naming variables using Hungarian Notation, format the variable names using Camel casing. With Camel casing, the first part of the variable name (the prefix that indicates the data type) should begin with a lowercase letter. All subsequent words in the name then begin with an uppercase letter. Consequently, variables have names such as intUserID and strUserLastName rather than IntUserID or struserlastname.

Table 18.2 lists various data subtypes recognized by VBScript, as well as the recommended prefix for variables designed to store each kind of data.

Table 18.2   Recommended Prefixes for VBScript Data Subtypes

SubtypeDescriptionPrefixExample
EmptyVariable is not initialized. Value is 0 for numeric variables or a zero-length string ("") for string variables.  
NullVariable intentionally contains no valid data.  
BooleanContains either True or False.blnblnIsUSCititzen
ByteContains an integer in the range 0 to 255.bytbytDepartmentNumber
IntegerContains an integer in the range 32,768 to 32,767.intintNumberOfDirectReports
Currency 922,337,203,685,477.5808 to 922,337,203,685,477.5807.curcurAnnualSalary
LongContains an integer in the range -2,147,483,648 to 2,147,483,647.lnglngSalesByDepartment
SingleContains a single-precision floating-point number in the range 3.402823E38 to -1.401298E 45 for negative values; 1.401298E 45 to 3.402823E38 for positive values.sngsngHourlyPayRate
DoubleContains a double-precision floating-point number in the range -1.79769313486232E308 to 4.94065645841247E 324 for negative values; 4.94065645841247E 324 to 1.79769313486232E308 for positive values.dbldblMeritPayMulitplier
Date (Time)Contains a date between January 1, 100 and December 31, 9999.dtmdtmHireDate
StringContains a variable-length string. Strings can be made up of any alphanumeric characters.strstrUserLastName
ObjectContains an object reference. An object variable represents an Automation object.objobjExcelSpreadsheet
ErrorContains an error number.errerrFindFile
ArrayContains an array of variables. Because arrays are designed to hold multiple objects, array names should always be plural. To maintain consistency with the other naming conventions, arrays should have two prefixes: arr to indicate the array, and a second prefix to indicate the data type.arrarrstrUserAccountNames
CollectionTechnically, a collection is not a variable subtype. However, it is listed in this table because you should use the col prefix to indicate collections. Collections are used extensively in system administration scripting.colcolInstalledApplications

Guidelines for Naming Variables

Both Hungarian notation and Camel casing provide basic rules for creating variable names. In addition to these fundamental principles, some other suggested guidelines for naming variables in VBScript are listed in Table 18.3.

Table 18.3   Naming Guidelines for VBScript Variables

Variable PropertyGuidelines
LengthCan be a maximum of 255 characters. However, variable names should be considerably shorter (32 characters or less). Shorter names are easier to read and easier to maintain. (Among other things, they take up less space on each line of code.)
First characterMust begin with an alphabetic character. A variable name such as User5 is allowed; a variable name such as 5User is not.
Special charactersMust not contain periods or spaces. Characters used in variable names should be limited to the following:

a z

A Z

0 9

In addition, variable names should start with one of the lowercase alphabetic characters (a z).

Case sensitivityNot case sensitive. intUserID and INTUSERID refer to the same variable value. However, it is recommended that you use Camel casing for all your variable names.
UniquenessMust be unique in the scope in which they are declared. VBScript allows you to use the same variable name more than once, provided the variables have different scopes (for example, they are declared within separate procedures or in separate scripts used as part of a library). You must, however, use unique global variable names throughout a script.
ConsistencyMany scripts require the same variables; for example, every Windows Management Instrumentation (WMI) script requires an object variable that represents the WMI service. Whenever possible, these names should be consistent among scripts; if you use the variable name objWMIService in the first WMI script you write, use that same variable name in any subsequent WMI scripts.

Reusing Variables

For the most part, you should not reuse variables during the execution of a script; each variable should represent only one item. For example, the following script code is valid. However, using the variable strName to represent, at various times, the user s first name, the user s middle initial, and the user s last name causes confusion.

strName = "Robert" strName = "M." strName = "Smith" 

To lessen confusion, use separate variables to represent each piece of data, as shown in the following script snippet. The code is easier to read and maintain, and there is no appreciable performance penalty for using three separate variables as opposed to reusing the same variable.

strFirstName = "Robert" strMiddleInitial = "M." strLastName = "Smith" 

Theoretically, reusing variables can help conserve memory. In the preceding script snippet, the variables strFirstName, strMiddleInitial, and strLastName must all be held in memory at the same time, even if they are used just once and then discarded. However, the amount of memory saved by reusing the same variable as opposed to using three separate variables is negligible. Memory conservation is usually not an issue in system administration scripts.

Loop variables, such as those in a For-Next loop, are an exception to this rule about never reusing variable names. Many script writers use i as the primary loop variable in scripts; additional, nested, loop variables take the values j, k, l, m, and so on. For example, the following script code includes two separate loops, both of which use i as the loop variable:

For i = 1 to 10     Wscript.Echo i Next For i = 1 to 10     intTotalCount = intTotalCount + i Next Wscript.Echo intTotalCount 

send us your feedback Send us your feedback « Previous | Next »   


Microsoft Windows 2000 Scripting Guide(c) Automating System Administration 2003
Microsoft Windows 2000 Scripting Guide(c) Automating System Administration 2003
ISBN: N/A
EAN: N/A
Year: 2004
Pages: 635

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net