Skip to main content.

Web Based Programming Tutorials

Homepage | Forum - Join the forum to discuss anything related to programming! | Programming Resources

Teach Yourself VBScript in 21 Days

Day 13 -- VBScript Standards and Conventions

DAY 13

VBScript Standards and Conventions


CONTENTS


On the preceding days, you learned how to write scripts. You have even learned how to use controls and programming techniques to create very powerful active pages through VBScript. However, you have not yet seen one of the most important aspects of producing good scripts. The quality of your scripts is directly influenced by the standards and conventions you apply when creating them. Today's lesson focuses on standards and conventions you can apply to your script development. You can improve maintainability, ease the debug process, and design and implement your code in a more organized fashion with good standards. All you have to do is apply a standard, consistent approach to the way you design your code.

This standard approach applies to everything from the way you name your variables to the type of comments you place in your code. It is possible to write functioning scripts without worrying about standards at all. You don't have to use standards for your scripts to work. As a matter of fact, the VBScript interpreter and browser that process your scripts don't care at all about standards. Standards are purely a human convenience for the sake of the programmer. Those standards and conventions, however, are a convenience that often enables you to produce better programs. Today's lesson will tell you everything you need to know to use standards and conventions to improve your own code and make it more maintainable.

Advantages of Standards and Conventions

Using standards and conventions has many dividends. Some are obvious and some are subtle, but they all add up to better scripts and saved time in the long run.

Code Maintenance Advantage



Most scripts that you create will have to be maintained. Software needs tend to evolve over time. A Web page that suffices today is a likely candidate to be improved in the future. The code that goes along with it will probably evolve to support added capabilities. For this reason, any script you write should be viewed as a piece of code that might need revisiting in the future. You can improve future maintainability by writing code with good standards today.

Perhaps the most recognized motivation for applying good standards is that standards make code much easier to maintain. Suppose another programmer has to work with your programs in the future. It will be much easier for her to dive in, understand, and work with your code if you have used a consistent naming, commenting, and structuring approach on all the code she must examine. This advantage holds true not only for someone else who might look at your code, but also for you. If you write a script today and then return to it a year from now to make a minor change, you will make that change much more quickly and safely if your code was written with standards you use all the time. If it was, you won't have to spend as much time refamiliarizing yourself with the standards, or lack thereof, in your year-old program. Good procedure names, variable names, and comments will bring you up to speed quickly when you must update code you wrote a while ago.

This better understanding of your code, in turn, helps you make a safer fix. You are more likely to introduce a bug if you are not completely clear on what the code is doing. Returning to code that was written with a good set of standards and conventions maximizes the chance that you will have a clear understanding of it.

Improved Team Communication

The benefits of standards and conventions become even greater if code will be shared between programmers. When this is the case, the task of understanding code becomes even greater, and the potential for misunderstanding somebody else's work is increased many times over. Different programmers have different styles and ways of approaching problems. Without a common approach, you can spend a great deal of effort simply trying to decipher what another programmer was thinking when he wrote a certain piece of code. Scripts written to standards provide these answers up front. If all the programmers exchanging code are all using the same standards, it is much easier to trade code because good standards make your code easier to read. If you have other programmers in your company with whom you will be sharing code, using identical standards guarantees quick and efficient communication of script logic and approaches.

Easier Debugging

Few would dispute the claim that code written with clear and consistent standards is easier to maintain. Standards provide another very important advantage that is often overlooked. Code that is clear also makes debugging programs much easier. When you are testing your program and something doesn't work right, think about the steps you'll probably follow to get to the bottom of the problem. You will need to review variables, trace through procedures, and take an overall look at what your code is doing. Good variable names, script structure, and comments certainly help with all those activities.

Faster, More Effective Code Implementation

Good standards pay off in program development in another, closely related, way. When you apply standards as you write your scripts, you will find that the scripts become easier to write. Because you are using a consistent approach for naming variables, objects, and procedures and you are commenting throughout the script, you will spend less time agonizing over these minor details. Instead, you will be able to immediately apply a standard approach without devoting thought to how to address those areas. As your scripts begin to shape up before your eyes, the clear documentation based on a standard approach helps you expand and flush out the scripts. A clear, well-understood foundation is easier to build on. Standards provide you with this clear foundation for your programs.

The Dangers of Not Using Standards

Using standards and conventions has many advantages. The advantages apply when you're creating your scripts and bring future paybacks when you're maintaining the scripts. Because standards provide benefits even at the time a script is created, it seems obvious that you should follow standards and conventions right from the start. Unfortunately, this is often not the case in software development. Many times, inexperienced developers perceive that it is quicker to plunge into writing a program without paying heed to standards. They omit comments for the sake of rapid coding and give no thought to descriptive procedure names to save slivers of time. They take similar shortcuts in all areas. The intentions are usually good when this happens; the programmer usually plans to go back and apply good comments and procedure names and other standards after the program is working. The typical reasoning is that the program is in too much flux to spend the time on standards initially, but the programmer can add comments and other cleanup after the fact once the program logic is firm.

Don't fall into this trap! Most programmers who intend to go back and clean up their code and make it consistent and standardized somehow never seem to find the time to do so. Perhaps more importantly with such an approach, you don't realize any of the benefits of standards as you create and debug your initial code. Using standards often forces you to stop and think about what your code is doing as you review procedures, variables, and comments. As a result, using standards from the ground up helps lead you to more logical thinking. If you cut the standards initially, you also cut these advantages.

Standards to Use

Once you've decided to use standards, you need to settle on a set of standards and conventions that you feel comfortable with and stick to them. It won't do you much good to use one set of standards today and then switch to a different style of standards next week and then choose a different approach the week after that. This defeats the very purpose of standards in the first place. The consistency that standards provide requires that you use the same standards from one project to another. The advantages of standards are even greater as code is shared between programmers. If programmers use the same standards, they stand to benefit more when scripts are shared.

Worldwide Standards?

VBScript provides a unique twist on the shared code model, too. One of the interesting aspects of VBScript is that source code for programs is now shared across the world as never before. Any Web page that uses VBScript essentially delivers the script source code to the user as a part of the page. If that user happens to be interested in VBScript, he can easily view the source of your scripts. Likewise, you can view the source of any other scripts on the World Wide Web.

Sharing and understanding one another's code applies not just across your own programs or your company, but also across the world. Given this tremendous source code sharing potential, you might expect that there would be one worldwide standard for scripts-and there is, in a way. Microsoft provides standard and convention guidelines for VBScript, which are documented on the World Wide Web.

Note
At the time of this writing, Microsoft's standards and conventions were documented as a part of its online VBScript documentation at http://www.microsoft.com/vbscript.

No universal law, however, requires every programmer to follow the Microsoft standards. The Microsoft standards are very good, but not all scripts will be created exactly to those standards. Other programmers might have their own extensions to the standards that they feel make their programs even more maintainable. In some cases, developers might not want the worldwide users of their pages to view their scripts at all. Their goal might be to ease maintenance at their own company and discourage unsolicited code lifting from their own scripts. The motivations for such a programmer to follow a single set of worldwide script conventions would be small. In other cases, a development team might decide that they just wanted to apply a subset of Microsoft standards, coupled with some of their own. Some companies might need a great many company-specific standards if their large projects are shared among many programmers and have some unique characteristics.

Adopting Standards That Are Right for You and Your Company

For all the reasons cited previously, you will probably find that the scripts you encounter on the World Wide Web take a variety of similar but slightly different standard and convention formats. Today's lesson provides one set of standards and conventions. It would be nice to say that the standards provided in this book, which are derived largely from the Microsoft standards, are the right set of standards and conventions to follow. It would be even greater if this book served as the universal set of standards and conventions that every VBScript programmer on the face of the earth was forced to adhere to! However, doing so would not be the right approach.

The standards and conventions you should apply to your projects are those that make sense in the context of your work. You should carefully consider the standards presented here, the standards online from Microsoft, and the standard styles you see in Web pages that use VBScript across the Internet. Put some thought into deciding on the set of standards you will use because it is a decision you will live with for quite a while. Perhaps your company has some special information that should appear in the comments for every procedure, such as the department and lead programmer responsible for producing that procedure. Perhaps you need to have variable names in a certain format to be consistent with an approach dictated by a Department of Defense contract. With many special cases, you might need to derive your own smorgasbord of standards from the base model.

If you don't have any such reasons, you can happily apply the following standards and conventions without modification. The closer you can follow the recommended industry-standard approach, the better. Once you settle on a set of standards and conventions, make sure it is consistent throughout your company and stick to it! With this approach, you will make standards and conventions work for you to improve your programs in efficiency, rather than work against you as simply a set of regulations you must follow.

Variables

You now have some background on standards and conventions and why they are important. It is time to consider the standards themselves. The first area of focus is variables, perhaps the most important place to apply standards because variables form the backbone of most programs. You will probably use a lot of them throughout your code. If you don't use variables correctly, the results can be devastating. Likewise, if you must maintain and modify code, it is essential that you understand what the variables do. As a result, the variable standards are aimed at clearly communicating the purpose and intent of variables.

Descriptive Variable Names

One of the easiest ways to make the use of a variable clear is to give it a meaningful name. Consider the following variable declaration:

Dim nm

This line declares a variable with the name nm. From this declaration, it is impossible to tell the purpose of the variable. The programmer could be using nm as an abbreviation for name, number, or the population of New Mexico. If you are maintaining this code listing and you see this variable declaration, what will go through your mind? You'll likely cogitate on the meaning of nm, making a few mental guesses. You will have to spend some time deciphering the code to figure out the true purpose of this variable. Suppose, on the other hand, that it had been declared in the following way:

Dim number

This declaration tells you a lot more. You can tell after reading the declaration that this variable will contain a number as opposed to a name, the population of New Mexico, or anything else. However, even this variable declaration could be improved. You can tell from the name that the variable declares a location in memory to contain a number, but you don't know what type of number.

If the variable name was expanded to include an adjective that describes the purpose of the number, you'd know much more about its context. Then you could tell even more about the variable at a quick glance when maintaining the source code. The following declaration communicates even more information about the purpose of the variable:

Dim Student_Number

This illustrates one important convention for naming variables: Make sure your variable names are descriptive. Include an adjective to make your variables readable in an adjective-noun format when appropriate. If it's been a while since your last English class and you're thrown by the adjective-noun rule, just remember that your variable names should clearly describe the purpose of the variable. In most cases, you can best do this by joining more than one word.

Mixed-Case Variable Names

Hand-in-hand with the convention of descriptive variable names comes another important guideline. Use mixed-case variable names to help make them more readable. Start each piece of the variable name with a capital letter. This naming approach makes it much easier to visually browse through your code when writing, debugging, or otherwise maintaining it.

This rule is easily illustrated through an example. Suppose that you have several variables, each of which is used to keep track of the number of students in a different grade. If you don't use mixed case but instead provide declarations, as shown in Listing 13.1, you can see it is rather hard to decipher the purpose of the variables. The words tend to run together, which not only affects the readability of those variables but also dilutes the overall clarity of the program as a whole.


Listing 13.1. An example of variable declarations not using mixed case.
Dim freshmanclassstudenttotal
Dim sophomoreclassstudenttotal
Dim juniorclassstudenttotal
Dim seniorclassstudenttotal
Dim totalhighschoolpopulation

If freshmanclassstudenttotal > 200 then
     msgbox "Insufficient seating for " & freshmanclassstudenttotal & _
     " students."
End if

It's not easy to see the meaning of these variables at a glance. They don't stand out when you view the source code. If you use mixed case and start each word with a capital letter, on the other hand, the meaning becomes much clearer, as shown in Listing 13.2.


Listing 13.2. Variable declarations using mixed case.
Dim FreshmanClassStudentTotal
Dim SophomoreClassStudentTotal
Dim JuniorClassStudentTotal
Dim SeniorClassStudentTotal
Dim TotalHighSchoolPopulation

If FreshmanClassStudentTotal > 200 then
     msgbox "Insufficient seating for " & FreshmanClassStudentTotal & _
     " students."
End if

The variable names in these examples are rather long to help highlight the point of how non-mixed-case names tend to run together. These are not bad names, but they could be better. Generally speaking, overly long names can impede readability and clarity by overwhelming the reader with too much information, just as overly short names sacrifice clarity because they're not descriptive.

Variable names should be long enough to convey their intended meaning without being too wordy. Consider Listing 13.3 and compare it to Listing 13.1 and Listing 13.2 for clarity.


Listing 13.3. Variable declarations with moderate length names.
Dim FreshmanTotal
Dim SophomoreTotal
Dim JuniorTotal
Dim SeniorTotal
Dim HighSchoolTotal

If FreshmanTotal > 200 then
     msgbox "Insufficient seating for " & FreshmanTotal & " students."
End If

You can see that these variables are much easier to read and interpret because they are shorter in length.

Variable Name Prefix

You've seen how to make a variable name convey more information. Even a descriptive name, however, doesn't tell you everything about a variable. For example, you can't tell if HighSchoolTotal refers to an integer total or if it could also contain a string. The programmer who uses this variable name might have included logic so that this variable is set to the string Unknown under certain conditions. You cannot tell the intended data representation of this variable just by looking at the name.

You can convey this information as part of the name. Many standards for other languages use a name prefix to provide data type information. Assume, for example, that the variable HighSchoolTotal should contain an integer only and was declared as type integer in another language. According to typical rules, it would be preceded by a lowercase int prefix.

A glance at the name intHighSchoolTotal tells you that the variable contains a student number that is also represented within the program as an integer. This type of naming convention fits somewhat better in other languages than it does in VBScript. Most other languages let you specifically designate the type of a variable. When you declare a variable with the Dim statement in Visual Basic 4.0, for example, you can specify in the same declaration whether it will contain integer, long, string, or some other type of data. With such a strongly typed language, it becomes very important to make sure your variables are used only for data of that type.

VBScript uses a somewhat different approach to variables, as you saw on Day 4, "Creating Variables in VBScript." All VBScript variables are defined automatically to have the type variant. A variant variable determines the type of data representation based on which assignments have been made to that variable. Even if you use int at the start of a variable name, there is no guarantee that the variable will be used only for integer data. You have to ensure the variable is used in that manner when you write the program. Suppose you named a variable to start with int, indicating it is an integer, to make the name more descriptive. Then you assigned string data to the variable at some point in your program. You would have made matters more confusing than if you had used no prefix at all. A glance at the variable name would tell you that it was set aside for only integer data. However, if you made a mistake and used it for integer and string data but proceeded with the assumption that only integer data was contained there, the task of debugging or maintaining your programs could become more time-consuming and difficult.

For this reason, a modified version of the standard prefix variable name approach is often the best for VBScript. This convention places a data-specific type of prefix such as int at the front of integer variables or str at the front of string variables only if the variables will be used just for that purpose. In addition, when the programmer uses such a prefix naming convention, she must make a special effort to see that no other type of data is assigned to the variable when creating the program. This is relatively easy because if the variable name starts with int, the programmer has a clear indication that integer should be the only type of legal data assigned.

However, the majority of VBScript variables might contain more than one data type representation at different points when the program is running. A variable such as HighSchoolTotal, for instance, might initially contain the string Unknown but at some later point in the program take the result of a calculation and contain an integer value. In this case, that variable can take both an integer and a string representation. It would be misleading to prefix it with either int or str.

Generally speaking, if you use good design and planning, you will know when you declare a variable what data type it will hold. In some cases, you might not know ahead of time all the forms of data a variant variable will eventually assume when you make the variable declaration. At other times, you might intentionally plan on a variant storing more than one type of data during the execution of the script. In either case, you can indicate this multifaceted role of the variable by designating the prefix for the variable name to be a v. This prefix tells readers of the program that the variable will handle multiple types of data by the specific intention of the programmer (rather than by accident). The declaration for HighSchoolTotal would be

Dim vHighSchoolTotal

When you see this variable or others like it in your program that start with the v prefix, you know that the programmer is explicitly indicating that the variable is not necessarily restricted to just one type. If you see a variable name that starts with int or str, however, you know those variables are expected to be restricted to just those types and that the program logic depends on that. The prefix table in Table 13.1 shows prefixes for all the various types you might want to designate.

Table 13.1. Variable name prefixes.

PrefixVariable Subtype Example
bln Boolean use of variant variableblnClassFull
byt Byte use of variant variablebytDownloadedData
dtm Date or Time use of variant variabledtmFirstSchoolDay98
dbl Double use of variant variabledblPiValue
err Error use of variant variableerrStudentRegistration
int Integer use of variant variableintFreshmanTotal
lng Long use of variant variablelngMichiganPopulation
obj Object use of variant variableobjArtClass
sng Single use of variant variablesngGradePointAverage
str String use of variant variablestrTeacherLastName
vVariant vClassGrade

When you use these prefixes as an everyday standard, you will find that they enable you to follow your code and the intended use of its variables much more easily. For example, consider the declarations in Listing 13.4. If this was code that you had written a year ago, could you tell from the declaration how you are using the variables in your program?


Listing 13.4. An example of variable declarations without a subtype prefix.
Dim StudentGrade
Dim TotalGraduates
Dim GraduationDate

It's not easy to tell the intent from these declarations. Suppose you examine the code and find the comparison of a date value to the string Unknown. Was that date variable intended to ever contain a string, or is this an error? You don't know the programmer's intention. Now assess whether you can tell the intent from the declarations in Listing 13.5.


Listing 13.5. Variables with a subtype declaration.
Dim vStudentGrade
Dim intTotalGraduates
Dim vGraduationDate


' ... Lines of code that update the variables would appear here

If vStudentGrade <> 'I' and vStudentGrade <> 0 then
    intTotalGraduates = intTotalGraduates + 1
    If vGraduationDate <> "unknown" then
        msgbox "you are still on schedule to graduate in " & vGraduationDate
End If

From just the declarations in Listing 13.4, you can't easily tell whether StudentGrade will contain just number grades or strings as well. It turns out that this variable contains both numeric grades and letters such as an I for incomplete. The variable declaration in Listing 13.5 makes this dual purpose clear because the variable name starts with a v.

Likewise, the data representation of TotalGraduates is not clear in Listing 13.4. Although you might assume from the name of the variable that it would be a number, you can't tell if the programmer has utilized a scheme where descriptive strings are assigned to the variable as well or whether the code keeps track of fractions of students. The more explicit intTotalGraduates variable name used in the subsequent listing lets you know that the programmer is using this variable only to store integer data.

Finally, the GraduationDate variable in Listing 13.4 doesn't tell you much about its intended representation. From the name, you might guess that it stores only date values. If you made this assumption, you would be wrong. Listing 13.5 shows this variable declared with the variant prefix, vGraduationDate. Because the variable name starts with v, you can tell that the programmer intends for the variable to use more than one type of data representation. As the code statements show, vGraduationDate stores the text string of Unknown when the graduation date is not clear and contains the normal graduation date when it is known.

The second set of declarations gives you a much quicker overview of how the variables are used. Of course, variable declarations should be accompanied by good comments describing the intended purpose as well, but a prefix is a good start for documenting and clarifying the way variables are used within a script. The variable name prefixes should be a part of any good VBScript standard. It is important to keep in mind, however, that just using a prefix doesn't mean that the code is guaranteed to use the variable in only that fashion. This will only happen when the naming convention is coupled with the programmer's vigilance. However, the informational benefit from the prefix standard is well worth the effort.

Scope Prefix

The scope prefix is one more special type of variable prefix. If you declare a variable right at the beginning of your script without placing it in a procedure, you can reference that variable anywhere within your script. It is said to have global, or script-level, scope. It is important to realize which variables are script-wide scope variables when you write your code. Generally speaking, it is a good idea to keep as many of your variables at the procedure level as possible and only use global variables for information that's important to share between procedures. Likewise, when you assign information to a global variable to share it with other procedures, you want to take special care that you do not wipe out previously existing values or set a global variable to a value not expected by other procedures.

In general, you should use a special level of awareness when coding with global variables. Most programmers apply this caution intuitively, but it is much easier to do if you have a clear indication of what your global variables are when you are changing your code. The scope prefix solves this problem. Any variables that are global in scope are preceded by s_. You can see this at work in Listing 13.6.


Listing 13.6. A code segment that uses a global variable.
Dim vStudentGrade
Dim vGraduationDate

' ... Lines of code that update the variables would appear here


If vStudentGrade <> 'I' and vStudentGrade <> 0 then
    s_iTotalGraduates = s_iTotalGraduates+1
    If vGraduationDate <> "unknown" then
        mfgbox "you are still on schedule to graduate in " & vGraduationDate
End If

Take a look at Listing 13.5, which does not use the global variable prefix. At first glance, this code does not quickly tell you whether the variables used are local to the procedure or global. You can always back up to the start of the procedure and look for Dim statements to figure this out; however, this can be time-consuming, especially if the procedures are large. Now take a look at Listing 13.6. Because the scope prefix was used here, it is very easy to tell at a glance whether a variable is global. If s_ does not precede the variable name, the variable is local. If s_ does precede the variable name, the variable is clearly global in scope.

Note
In VBScript, any variable that is declared outside of a procedure has script-level, or global, scope. Any code can access and modify this type of variable anywhere within the page. This includes the same script where it was defined or other scripts if more than one script is included in the page. It also includes any VBScript code embedded in a control tag. For example, in the input line
<input type="button" value="Yes" name="cmdYes" onclick="msgbox_ s_Var1">
the value of s_Var1 would be displayed correctly even though that variable is referenced outside of the script that defined it.
Script-level variables should always start with the s_ prefix. This indicates a variable can be referenced anywhere on the page. Variables cannot be shared between different pages. The only other type of scope a variable can have is procedure level. The absence of a scope prefix indicates a procedure-level variable.

You can see in this example that s_iTotalGraduates is a global variable. Because of the script-level scope naming convention, you know that it is declared in a manner such as the following:

<script language="vbscript">
<!--
Dim s_iTotalGraduates

A scope prefix is easy to declare and will really improve the clarity of your script programs if they grow in size beyond the trivial level. As with the data subtype prefixes, there is nothing magical about scope-level prefixes. A programmer could use a prefix incorrectly. You might use the scope prefix on a local variable, which would be quite misleading when programs are reviewed with the assumption that s_ indicates global variables. Just like before, you must have an awareness about applying this prefix correctly along with your standards and conventions. If you have that awareness, these prefixes work well, and you should use them routinely.

Comments

Good comments are perhaps the most important part of script standards and conventions. They also pose one of the biggest challenges in defining standards. The questions of what constitutes a good comment and what level of comments is ideal can be quite subjective. Good comments depend largely on the situation. If you do a good job structuring your code and providing descriptive variable names and procedure names, this should decrease somewhat the number of comments it takes for the reader to get up to speed with your program. Likewise, if you make good use of prefixes, the reviewer of your code, whether it's a fellow programmer or you yourself some months down the road, will have a greater amount of insight into variables. In some respects, the need for comments is decreased when you follow standards in other areas of code, but some comments are still essential.

A comment that accompanies a variable and describes the purpose of the variable can be a great help to those struggling to understand a program. The comment delimiter as you have seen throughout the examples so far is the single quotation character ('). You can use this to set off entire lines. All text that follows this symbol on a line is treated strictly as a comment and not acted upon by the VBScript run-time interpreter.

You can also put a comment at the end of a statement line. After a Dim statement, for example, you can have on the same line a ' followed by comments that describe that variable. You should follow this convention for all but the simplest of variables. If the purpose of the variable is glaringly clear from the variable name and the code where it is used, you can bypass the variable comment. For example, if you have a variable used in a For…Loop index declared at the top of a procedure and that procedure has only five lines of code, it will be fairly obvious to the readers of your code the purpose of that variable. This assumes you have given the variable a descriptive name as well.

For any variable that does not have such a clear and simple application, some descriptive text should appear after it to elaborate on its purpose. If a variable is central to an entire algorithm and has some special use or if you should assign only certain values to it, then it might be appropriate to precede the variable Dim statement with several lines of comments that elaborate on its use. If you have several related variables and the reader should understand the relationship of all of the variables when reviewing any of them, those variable declarations should be grouped together. The entire group should be preceded by a comment that describes any important relationships. Look at the following code and determine what you can tell about these variables:

Dim s_intAcademicAdvisingCode

Dim s_strStudentID
Dim s_strStudentLastName
Dim s_strStudentBuilding
Dim s_strStudentLocker

As you can see, even though the variable names are descriptive, you can't tell a lot about what these variables do in the program. Without good standards, you would have to dig through the code to determine how it uses the variables.

Now look at how some good comments can provide this information even before you dig into the following code:

' code used to reflect current academic advising status
'   0 = status is undetermined at this time
'   1 = student needs academic advising
'   2 = academic advising requirements fulfilled
Dim s_intAcademicAdvisingCode

'Student id is assigned by a function which returns an encrypted result based
'   on the student's last name, building, and locker. If any of these elements
'   have not been assigned then the student id cannot be generated for the student.
Dim s_strStudentID 'the id number for the student returned by function GetID
Dim s_strStudentLastName 'the last name the student is registered under
Dim s_strStudentBuilding 'the name of building which contains the student's home room
Dim s_strStudentLocker 'the student's locker number

You can see that the information in the second segment is much more descriptive than that of the first. A glance at this listing provides fairly complete details on how these variables will be used in the program and what they are intended for. Notice that strStudentLocker is pretty fully described by its name alone. The comments to the right of the Dim statement don't add that much description. This is one area where you could leave out the comments. Other than that, the comments shown here enhance the program maintainability considerably. A good comment strategy such as this should be the backbone of your standards and conventions.

Constants

Constants are symbolic names for values that never change within your code. For example, if the sales tax were 4 percent, you could represent that in a constant and your code would base its calculation on the symbolic name SALES_TAX rather than the number .04. If you used the constant throughout your program and the sales tax changed at some point in the future, you would only have to modify the one line of code that declares the constant. All the other lines that reference the constant could remain unchanged.

Most languages provide direct support for such constants. VBScript provides no such support, as you saw on Day 4. If you want to use a constant, you must use a variable to represent it. You declare the variable through a regular Dim statement and then assign the value of that variable once in the startup area of your script. Thereafter, you can refer to the constant value. If you are treating it as a constant, you should never modify the value.

Most languages do not enable you to change the value of a constant. With VBScript, you can change the value because a constant is really just a variable. When you use a variable-based constant in VBScript, you are simply using a variable that you make sure not to change to provide yourself with a simulated constant. Most languages use the convention of all capitals to make a constant value distinct in the code. What about VBScript? You already have a nice set of variable conventions that don't have any provisions for constants, but you can easily extend the variable conventions discussed so far to encompass constants. If you're going to use a variable as a constant, you should declare it in all uppercase letters. This signifies to the reader of the source code that it is a value that you intend to never change within the program.

Common convention in other languages is that constants usually do not have type or scope prefixes. However, there is no reason not to add this to the VBScript convention you use. Prefixes can provide valuable information, even with constants. Listing 13.7 shows an example of a global constant.


Listing 13.7. An example of a global constant declaration.
<script language="VBScript">
<!--
    Dim s_sngSALES_TAX ' CONSTANT Sales Tax Rate
    Dim s_sngCOUNTRY_A_CONVERSION_RATE ' CONSTANT for the conversion rate for
                                       '   cou ntry A to be applied to the dollar

    ' Set up values for variable constants which should not be changed anywhere
    s_sngSALES_TAX = 0.04 'CONSTANT initialization
    s_sngCOUNTRY_A_CONVERSION_RATE = 1.56 'CONSTANT initialization

The sng prefix tells you that this constant contains a single data subtype representation rather than an integer. It becomes a very easy matter to understand where a constant is and what it represents if you declare your constants in this manner. Consider the following code:

vCurrentSale = iItemPrice * s_sngSALES_TAX
vConvertedDollars = intCurrentDollars *s_COUNTRY_A_CONVERSION_RATE

If you follow the constant conventions recommended here, the use of constants will jump out at you as it does in the previous code segment. Several things are clear at a glance in this code. It uses constants that are global in scope. You even know the type of the constants. This type of consistent approach to using constants will make maintaining your code much easier for the same reasons that the variable convention pays off.

A Convention for Intrinsic Constants

Some necessary constant values are dictated by the VBScript language itself. For example, a certain value is expected for the second parameter of the VBScript MsgBox function to cause it to display yes/no buttons. A different value is expected to cause it to display OK. For example, you can use vbYesNo to request a message box with yes and no buttons, as detailed on Day 14, "Working with Documents and User Interface Functions." The Visual Basic 4.0 language automatically defines these values as a special kind of constant called an intrinsic constant. No declarations are needed to use these constants. The constants start with a vb prefix to indicate they are values expected by Visual Basic, such as vbOkOnly.

VBScript does not provide such automatically defined intrinsic constants in the current beta version. However, you can declare your own intrinsic constants as needed by using variable declarations, as shown on Day 14. For this type of constant, it is recommended that you use the same vb prefix naming convention used by Visual Basic 4.0. When you reference intrinsic constants in code, you should use the approach defined by Microsoft for the intrinsic constants. Intrinsic constants start with a lowercase vb and then use mixed case for the remainder of the name. For intrinsic constants, the vb prefix indicates that this is a Visual Basic intrinsic constant, and the mixed case improves readability.

This serves a couple purposes. It helps you distinguish which constant values are required by the language (vb prefix names) versus which constant values are defined by you for your own constant purposes (all-uppercase constant names). Also, if VBScript does add support for automatically defined intrinsic vb constants in the future, you can simply remove your declaration statements and your code will already take advantage of the expected names. And if you ever need to port code between VBScript and VBA or Visual Basic, the porting will go more smoothly if you have used the same constant names supported in those other environments. A file of such vb constant declarations is available on the CD-ROM that accompanies this book under \shared\tools\constants.txt. These declarations are compatible with the values required by the VBScript language and use the same names as the automatically defined constants of Visual Basic 4.0, so you can be assured of maximum future compatibility. You can double-click on this file to bring it up in Notepad or another text editor, and then copy and paste the declarations you need into your VBScript code.

Objects

Now you have seen details about standards and conventions for referencing variables. Other elements that your code will frequently reference are objects. Day 10, "An Introduction to Objects and ActiveX Controls," looks at how to insert objects such as controls into your Web page and then reference those from your code. That lesson describes how you can name an object through its ID attribute. The name that you specify as the ID is the name you use in code when referring to the object. You have also seen many different types of ActiveX control objects, including text boxes, timers, new item controls, and many, many more. On Day 18, "Advanced User Interface and Browser Object Techniques," you will find out about many more host environment objects automatically defined by the browser. What if you use many of these objects on one page? How do you keep them straight in your code statements? The answer, of course, is more conventions!

The good news is that the approach for objects is very similar to that of variables. Descriptive names are essential. In many cases, it might be helpful to use two words to describe an object; one is the descriptor and one is the noun. You don't need to indicate whether an object is global in scope because every object declared through the object tag is global by definition. Likewise, all the automatically declared browser objects you will learn about on Day 18 are global in scope. As a result, you don't need to worry about the s_ prefix. You do need to worry about an object type prefix. Objects come in a variety of types, and you indicate that an entity is an object and the kind of object it is through the prefix. Table 13.2 shows the prefixes you can use for some of the more commonly encountered objects.

Table 13.2. ActiveX control object prefixes.

PrefixControl Object Type Example
chk Check boxchkOrderPlaced
cht Chart or graphchtStockPrices
cmd Command buttoncmdPlaceOrder
lbl LabellblHeartRateFeedback
obj Generic ObjectobjWindowDocument
opt Radio button (also called option button)optSmallSize
pre PreloadpreCompanyLogo
tmr TimertmrPulseRateMeasurementDuration
txt Text boxtxtShoeSize

These prefixes provide descriptive, meaningful names for your objects. You should give the objects descriptive names that are combined with their prefixes. Notice that the names for some objects, such as the command button object, should be descriptive of an action, as in cmdCalculate. Other objects that contain user-supplied information but are not directly associated with an action, such as a text box control, should have descriptive names similar to those of variables, as in txtShoeSize. You should make your own customized object-naming convention list a part of your standards because this is one part of your standards in particular that is likely to evolve. Over time, more and more controls of various types will probably become part of your programming repertoire as more controls become available. You will want to expand your standards to make sure to include standard prefixes for any controls you purchase in the future for your development.

Table 13.2 includes the subhead "Prefix," but the definitions include those for intrinsic HTML elements that are automatically defined, such as text box and check box controls, in addition to those that you explicitly define with the objects tag. These are a special type of object, and conceptually, your code treats them the same.

The obj tag is a generic tag that can be used to refer to any object. There is a virtually unlimited number of types of objects that you may encounter. Each new control created by vendors is a new kind of object. You may find that if you try to come up with a new meaningful prefix for each control you use, your code soon becomes filled with variable prefixes that confuse and befuddle you rather than serve the intended purpose of clarifying your code! For that reason, it is a good strategy to prefix the many objects under the spectrum that aren't addressed in Table 13.2 as obj. If you couple that with a meaningful name, then at a glance you can tell everything you need to know about the identifier. You know from the prefix that it's an object, and you know what kind of object from the remainder of the name. This can encompass ActiveX controls; browser objects such as windows, documents, frames, and the navigator; Java applets; and more. On the other hand, if you use one specific type of object frequently, it may warrant designating a standard prefix for it to help it stand out in your code. Remember, the overall goal is that you want prefix payback without prefix clutter!

Good naming conventions for objects are just as important as-and in some instances, more important than-naming conventions in other areas. This is because you can declare objects in many different places throughout a script. Keeping them straight can become a bit of a maintenance challenge as your Web pages grow larger. If you use good naming conventions, you have immediate feedback about exactly which types of objects the code is using and whether they are implicit or explicitly declared. Consider the following line where neither prefixes nor descriptive names are used in referring to an object:

feedback="normal"

This statement doesn't tell you too much without additional digging. A little dose of conventions makes it more descriptive even without looking further into the source code:

lblHeartRateFeedback.caption="normal"

This line tells you that a label object is used and provides more details on the type of information displayed in that label. Just the application of standard naming conventions to this statement is enough to tell you that the line fills a label with heart rate feedback. The modified statement also illustrates that object names, just like variable names, use a mixture of uppercase and lowercase for clarity and reading. The appropriate use of conventions in referencing objects can contribute a lot to the clarity of your overall script.

Procedure Declarations

By now you've seen many illustrations of how clear documentation and a consistent approach pay off. These same benefits hold true for procedure declarations as well. Several different areas of procedure conventions are important.

Descriptive Names for Procedures

Once again, descriptive names are the first step to a good, consistent approach. Because procedures carry out some action, the descriptive names have a slightly different focus. Procedure names should begin with an action word. If you saw a code statement that made a call to a procedure named GPA, it might not mean that much to you. Even if you realized that GPA stands for grade point average, you don't know whether this procedure displays a student's grade point average or prompts them for it or performs some other activity.

A better name for the procedure can make its intent very clear. It is no surprise that a procedure named CalculateGPA calculates a student's grade point average. This is one of the standard areas that you should never bypass. If a procedure does not start with an action word, the description name is generally not adequate. Procedure names, like variable names, should appear in mixed case to improve readability of the word components that make up the name.

Prefixes for Procedures

Prefixes indicating data subtypes of return codes are not generally used for procedures, although in some cases, this could add further clarity. Declaring functions with the appropriate prefix of the type of data that they are to return makes those function names even more descriptive. Because a programmer commonly refers to function description comments when reviewing function call statements, good comments usually suffice.

Procedure Comments

A procedure declaration should have a comment line that summarizes in one brief sentence the purpose of that procedure. There should also be a comment line that describes any arguments whose purpose is not immediately obvious from the arguments' names. Then you should have a line that specifically describes return values from the function if this is a function type procedure. It is important to document the return value for error conditions as well as normal conditions when appropriate. Following these comment lines should appear another descriptive block of comments for procedures that are of substantial size or complexity. The description area explains in detail the logic or algorithm of the procedure.

When writing these comments, the programmer should keep in mind that the reader of the comments will already know VBScript. You should make this assumption when writing comments to avoid unnecessarily over-commenting or adding comments of little value. For example, you don't need to describe the manner in which a For…Next loop works just because a For…Next loop appears within the algorithm. You have to make some basic assumptions about the programming level of the reader; otherwise, you would end up writing a book like this with each program!

Although the intrinsic VBScript syntax is a well-defined, finite topic that you can expect the comment reader to understand, control usage is not. There is no limit in sight to the number of controls that might evolve, and you shouldn't assume that your comment reader is aware of anything other than the basic ActiveX controls such as those covered in this book. Although it is a good hunch to assume that your reader knows VBScript, it is not a safe hunch to assume that your reader knows the usage of every control that your code references. If your code uses an ActiveX control, the reader of your comments and code might not be familiar with that control's functionality, properties, or methods. For that matter, if you are making a change to your script a year after it was written, you might not remember the characteristics of a control if it is one you don't use very frequently.

For this reason, it is appropriate to document in your comments any special uses of a control within the script. Descriptive comments are perhaps more subjective than any other standards area. A brief, well-done description can save time over the code maintenance life of a script. However, a poorly thought-out description or a few lines of description that you provide just for the sake of complying with a standard are often of little value. The best standard for the description area is to provide a description that illuminates the reader's understanding of the source code where necessary and appropriate.

Good Procedure Conventions in Action

Following good standards is a combination of using descriptive variable and procedure names and using comments. A script with very good names and a few appropriately placed comments by key declarations can be much more maintainable than a script with poor names and many lines of poorly composed comments. The best standard for procedures is to use descriptive names and start them with an action word in every case. Always include at least a one-line comment with the procedure declaration that briefly describes what it does. If the procedure has arguments or returns a value, include lines that outline that. Then include additional lines that describe the purpose, if needed. If you follow these guidelines, readers of your code will have a good feel for the capabilities of a procedure just by glancing at the top of a procedure declaration. They can dig deeper into the code when needed, but they won't be forced to dig through and decipher a procedure when they simply want to get a feel for what it does.

Listing 13.8 shows a good procedure declaration.


Listing 13.8. A procedure declaration that conforms to standards.
Function CalculateGPA(intGrade1,intCredits1,intGrade2,intCredits2)
'Purpose: Calculates grade point average for a two class-load term based on
'    the student's grade and credit hours for each of the classes
'Arguments:
'    intGrade1,intGrade2 - integer grades for class 1 and class 2 of
'        the student. These will be 4 for A, 3 for B, 2 for C, 1 for D, 0 for E
'    intCredits1, intCredits2 - the number of credit hours for each of the classes,
'         ranging from 1 to 3 hours
'Returns: student's grade point average in single subtype ranging from 0 to 4
'Description:
'    Calculates the grade point average based on the average grade earned per
'    credit hour. Each class's grade is weighted by the number of credit hours
'    for that class to derive an overall average GPA for the student.

Within Your Code

You've seen how to use good conventions for variable names, constants, objects, and procedures. All that's left is the code itself! Most of the steps you can take to write good, maintainable, consistent code have already been described in terms of the other areas. Comments are critical. The same guidelines for procedure comments apply to code in general. Brief comments should accompany any block of code whose purpose is not obvious by the syntax and variable names. Again, the purpose of your comments should not be to explain VBScript. It should be to explain the nature of the problem, the reasoning and algorithms of the code, and the use of any unconventional controls.

There is no set guideline that works in every case for the number of comments required to describe your code statements. Generally, a comment for every line is overkill; but with complex code, this might be appropriate. The best approach is to use a brief comment for a group of statements that serve a common purpose. The placement of comments can help make your code more or less readable, too. Code statements are generally not as readable if comments appear at the end of a statement line. Comments nestled among code statements tend to stand out much better when they appear on a line of their own.

Using white space is another technique that can improve the readability of your code. Using white space simply means inserting a blank line in your code to separate one conceptual block of code from another. This makes each related group of statements stand out more as a separate entity. Some standard recommendations downplay white space for the sake of keeping the overall lines in a Web page as small as possible. It's true that each line of white space increases the overall number of bytes in the script, but the additional overhead from good use of white space is negligible. The maintainability advantages of good white space far outweigh the disadvantages.

Another technique to make code more readable is using proper indentation. We've used indentation throughout the samples in this book. Good indentation consists of spacing over statements that are logically subservient to a high-level statement. For example, in an If…Then conditional, the statements inside the conditional are only performed if the condition is true. Indenting those statements four additional spaces makes it clear that the If statement always gets evaluated and the indented statements only get executed in certain conditions. Typically, you use four spaces for each level of indentation. Comments that follow a procedure declaration are usually indented one space from the procedure name.

You should also write VBScript syntax keywords consistently. The standard approach is to used mixed case. If…Then is more readable than if…then. The purpose of standards is to enhance the clarity and readability of code. You can use development tools for this purpose as well. Some commercial code editors can, with some effort on the part of the user, be custom configured to highlight VBScript keywords in a given color, and with time you can expect more and more VBScript-targeted tools to emerge in this category. Tools such as Microsoft's Control Pad Editor, described in Day 2, "The Essence of VBScript," also can lead to better code through features like the VBScript Wizard, which provides some automatic code generation. Such tools go a step beyond standards because it's not an action you can control in the way you write programs. However, it is important to realize that to some extent, standards and code viewing and generation tools are aimed at the same purpose-making the maintenance of code easier and more efficient.

Note
You can find more details on some of the tools in this category at www.doubleblaze.com as they emerge.

A good standard approach for your code statements like that described here is essential. This area in particular pays off when you're writing programs for the first time as well as when they're maintained in the future. If the program is easy to read, it will be easier to spot bugs and improve your logic as you write and work with the code. If the program is hard to read, it will tend to mask bugs and obscure your logic as you compose the program. Notice the code in Listing 13.9.


Listing 13.9. An example of code that was not written according to standards.
if intQuantity < 5 then
msgbox "additional $10 shipping charge will be applied for low volume order"
intOrderSurcharges=intOrderSurcharges+10
end if
if blnPromotionalOrder <> vbTrue then
msgbox "$20 handling fee will be applied"
intCharges=intCharges+20
end if
intTotalPrice = intCostOfOrder + intCharges
intTotalCost = intTotalCost * sngYEN_CONVERSION_FACTOR

You can see from the preceding code segment that it takes a little bit of strain and digging to understand what the code does. Now take a look at the readability when a good dose of standards has been applied in Listing 13.10.


Listing 13.10. Code that has been written with good adherence to standards.
'calculate the low volume order surcharge if needed
If intQuantity < 5 Then
    msgbox "additional $10 shipping charge will be applied for low volume order"
    intOrderSurcharges = intOrderSurcharges + 10
End If

'Add the standard handling fee unless it is a promotional order
If blnPromotionalOrder <> vbTrue Then
    msbbox "$20 handling fee will be applied"
    intCharges = intCharges + 20
End If

'Now calculate total price in yen using item cost computed earlierÂ
plus surcharges
intTotalPrice = intCostOfOrder + intCharges
intTotalCost = intTotalCost * sngYEN_CONVERSION_FACTOR

You can see that it is much easier to read the second segment than it is to read the first. Unless you have a real penchant for puzzling other programmers as well as yourself, the second approach is clearly the recommended one.

Script Structure

A few guidelines pertain to overall script structure. An overview comment should appear at the start of the script. After the script tag <SCRIPT>, an HTML comment should appear on the next line. The use of the HTML comment indicator was discussed on Day 3, "Extending the Power of Web Pages with VBScript." This tag (<!--) should start a script so that browsers that don't support VBScript will treat the whole VBScript as a comment and not display it on screen. The corresponding ending tag (-->) then appears at the end of your script to terminate this comment behavior for browsers that do not support VBScript. Immediately after the comment tag at the start of the script should come an overview comment that states the overall purpose and goals of the script. It might seem to you that the goals of the script would be obvious, but if your page is large, it might not be immediately obvious to a reader who is trying to sift through the entire page. Code can be associated with many different aspects of a page and more than one script can appear in a page, so it is important to describe exactly what purpose a specific script serves.

Generally, your code should appear at the bottom of your page right before the </BODY> end-of-body tag. There are several advantages to this approach. This makes it very easy to locate all the code in a page. And there are some situations, particularly dealing with VBScript code intended to run as the page loads, in which the code must appear after the objects it references. Placing code at the bottom of the script frees you from any such concerns.

You can insert multiple scripts in your Web page. When possible, you should use one script rather than multiple script sections throughout the page. Using multiple scripts makes it that much harder to understand and maintain the code. In most cases, there is no reason not to combine multiple scripts into one script. One of the reasons that multiple scripts are sometimes used is that you can set up scripts to handle specific events, as in the line that follows:

<SCRIPT Language="VBScript" event=OnClick FOR=cmdButtonName>

This dedicates the entire script to that event, as was described on Day 7, "Building a Home for Your Code." If you have more than one event to catch, you'll need more than one script with this approach. However, you can easily convert such an event to a subroutine within one main script. The same event that is handled in a separate script can be converted to a subroutine that is named as follows:

<SCRIPT LANGUAGE="VBScript">
Sub_cmdButton_OnClick

The name assigned to the subroutine will cause it to be called as the event handler for the OnClick event of the button cmdButton. Using this approach, you can group all your event procedures in one script. A quiz solution at the end of today's lesson illustrates this approach.

You can also associate code with other input controls themselves, right on the input control definition line. This technique was addressed on Day 8, "Intrinsic HTML Form Controls." This line calls a message box right from the input control tag:

<INPUT TYPE="Button" NAME="cmdMyButton" LANGUAGE="VBScript"
  OnClick="msgbox 'VB Rules': msgbox 'And it is fun!'">

Similarly, this line calls code directly from the body tag:

<BODY LANGUAGE="VBScript" OnLoad="msgbox 'VB Rules': msgbox
  'And it is fun!'">

In general, avoid the temptation to blend code directly with input control definitions or other elements like this. The more you can group code together in one consolidated script block, the easier your maintenance will be. The code in the input control example above with the input button could be replaced by a subroutine named cmdMyButton_OnClick in the main script body, and the input tag could simply read

<INPUT TYPE="Button" NAME="cmdMyButton">

The code in the body tag example could simply be moved to the main script and placed at the start of the script, before the procedure definitions. Then it would get called at the end of the page load and the body statement could simply read

<BODY>

In both of these cases, you avoid tangling up code with your HTML statements, spread across your page. Instead, you consolidate the code into one well-defined place in your page-the script section. You've laid the groundwork for pages that are much easier to understand, debug, and modify in the future.

Startup code itself warrants some special consideration. Any code in your script that is not in a procedure is executed when it is sequentially encountered as the page loads. As a result, it is very important to know what and where this startup code is. Typically, you should include it right at the start of the script, explicitly commented with a line that says Startup code. But rather than have a large block of startup code, it is better practice to just have one statement that calls a StartUp subroutine you define. The name can be anything you define, but it is important to use the same name consistently across your pages for easiest maintenance, and StartUp is recommended for consistency across the industry (or at least across the pages of readers of this book!). This StartUp subroutine then becomes the well-known place for any page initialization code, consistent from page to page and project to project.

A previous example from today illustrates that you can associated startup code directly in the body tag. This opens the door to the possibility of calling the StartUp subroutine there, with a statement such as

<BODY LANGUAGE="VBScript" OnLoad="StartUp">

This works as well, but in some respects, it is a much less maintainable approach. If your startup code is clearly designated at the top of your script section, it is perfectly clear when you look at the code what startup code gets executed. If you use the practice of triggering your startup code from the body tag, on the other hand, a reader could review the script statements and never realize that some routine there had special startup characteristics. So the <BODY OnLoad=> approach to indicating a starting procedure can be slightly less clear. If you do use that approach, make sure to use ample comments in the script to indicate the startup behavior caused by the body tag.

Note
It is interesting to compare the behavior of a StartUp subroutine called from the <BODY OnLoad=> tag versus a StartUp routine defined at the top of a script appearing immediately prior to the end of the document's closing </BODY> tag. If you use both of these methods in the same script, you will find that the <BODY OnLoad=> subroutine gets triggered first, followed by the subroutine defined in the script at the end of the document. When you consider that a page is processed sequentially on load, this makes intuitive sense.

Concerns

You have heard a lot of reasons for using standards and conventions. If you've talked to many other programmers or thought much about these issues, you might also have some concerns about the disadvantages of adherence to standards and conventions. Several concerns often come up in relation to standards.

Myth: The Overhead Penalty Outweighs the Advantages of Standards

One of these concerns is quite unique to the nature of VBScript-whether you should avoid using white space and plenty of comments because it makes the Web page size larger. Most programming languages are compiled into a final executable and the end user pays no price for size of the source code. However, in the case of VBScript used with Web pages, the end user is affected. If you put many hundreds of lines of comment into the script on a Web page, the end user will have to download a Web page that is many hundreds of lines larger.

Should this make you avoid comments? The answer is no. The advantages of writing good code through comments far outweigh the disadvantages of this overhead penalty. The extra download time caused by including additional bytes of the script to download will usually be negligible and not something your user will perceive. It would take many lines of comments to add up to the several kilobytes of data that would be necessary to introduce a noticeable wait even on systems connected by the slowest of means. On the other hand, you don't want to turn the comments for your scripts into gargantuan guides to every aspect of a project.

You should keep in mind the download overhead factor and avoid the temptation to add unnecessary fluff or extensive documentation to scripts. If you feel that a lot of documentation is needed to supplement a script, it might be better addressed in a separate design document you could maintain elsewhere. Many projects use a design document approach to document overall goals for a project. Then the developers proceed to build the specific programs or scripts, including only comments relative to that specific script in the script itself. This is a good approach for larger projects and can cut down on extensive comments within the scripts without sacrificing the advantages of documentation.

Myth: Standards Slow Me Down

Another common concern about standards and conventions is that it takes more time to write code when you must worry about making it adhere to standards. This argument is based on a shortsighted view. If you put careful thought into following a good set of standards and conventions and carefully documenting your code through good comments and procedure and variable names, it might indeed take you longer to type in the keystrokes of your program. When this time penalty is compared to the significant maintenance, debug, and even design time benefits that result from good documentation, the truth becomes clear. Carefully adhering to standards and conventions saves time over the long run.

Trying to bypass standards and conventions is a lot like trying to speed up your vacation trip by skipping the visit to the gas station. You'll get on the road more quickly, but you're more likely to run into delay before you reach your final destination when you run out of gas. A good way to make sure that the time taken to comply with standards is productive is to keep in mind that the purpose of your standards and conventions is to increase efficiency overall. If one of your standards seems particularly troubling and time-consuming, you should examine it with respect to your overall standards. If you don't see the benefit of a certain standard, don't use it, but carefully weigh the pros and cons before making such a decision.

The Non-Myth: Standards Constrain Me!

Finally, perhaps the most common concern about standards is that they require discipline on the part of the developer and can make the developer feel constrained. This is no myth but is the cold hard truth, and it is true for good reason. Discipline and constraint is not always a bad thing. Producing software is a creative art, but it is also a logical science. It is something that affects other people and sometimes businesses and their bottom line. Although it might be more fun to program free-form with no thought for the future, it is not the best programming practice.

Paying the price of a slightly more disciplined and constrained approach is well worth the effort. This is especially true because the benefits of following standards and conventions don't mean any loss of creativity or flexibility in design. You just exercise your creativity under more controlled circumstances. The graffiti artist who plies his trade by recklessly defacing buildings has no more claim on creativity than the professional artist who sketches within the borders of a notepad. The professional artist simply has more foresight. The benefits are there for the taking for whoever is wise enough to apply them.

Summary

Today's lesson discusses many aspects of standards and conventions and points out the advantages to using standards and conventions. Code that conforms to a common set of conventions will be easier to maintain, easier to debug, and even easier to write. Often, the act of writing good code as you go along leads you to clearer organization and structure. One of the challenges for getting started with standards and conventions is deciding exactly which standards to use. A good general recommendation is to follow the Microsoft guidelines as closely as possible, extending them where you feel it is necessary for the sake of your project. Today's lesson presents a detailed set of such guidelines.

The lesson first introduces the standards for variables. One important aspect of declaring variables is giving them meaningful, descriptive names with an adjective as part of the name, where appropriate. You should name variables in mixed case to enhance readability. You should also use prefixes with variables, where appropriate, to indicate the intended data subtype representation of the variable. However, this technique is a bit harder to apply in VBScript than in other languages because VBScript is not a strongly typed language. As a result, an important part of the standard approach for VBScript is to use the v prefix to indicate a variable is a variant with a subtype that might change representation. You should use a scope prefix that consists of s_ to indicate global variables that can be referenced from any procedure.

Comments can help a great deal in highlighting the purpose of variables. You can use comments at the end of a variable declaration on the same line as the Dim statement. You can also use them to describe a group of related variables. Such related variables should be grouped together, and any relationships between the variables should be described in the declaration comments. Such comments are provided in a line or group of lines preceding the variables.

Today's lesson also examines constants. VBScript constants are really variables but can still be indicated separately by using uppercase letters for the constant names. Intrinsic VBScript constants are not defined by the user and will always be preceded by a vb. Object names should be similar to variable names. You should use mixed case for readability. You should also use descriptive prefixes to indicate the type of the object. For example, an intrinsic text box control would have a name that starts with txt. An ActiveX control object such as a timer would have a name that starts with tmr. In this manner, the type of object is easily apparent from looking at the source code.

It's also important to provide a standard approach in procedure declarations. Like variable and object names, procedure names should be descriptive. However, procedure names should start with an action type word to indicate the action performed when the procedure is called. It is important to use comments in a procedure declaration, including at least one line that briefly describes what the procedure does. If it's appropriate, you should provide additional lines describing arguments and return codes. If the procedure is not trivial, you can provide additional lines of description in the procedure comment area at the top of the procedure. In any comments, it is safe to assume that the reader knows VBScript. Comments should elaborate on aspects of algorithm, logic, or infrequently used control aspects.

The guidelines for code statements are much the same as those for procedures. You should use good comments, which can refer to groups of statements where appropriate. You should also use indentation and blank lines to set apart code statements and make them clearly readable where needed. Show VBScript keywords in mixed case. Some utilities can also help with the maintainability of code by highlighting keywords in certain colors.

Finally, today's lesson addresses some concerns about following standards and conventions. It is true that to a certain extent, adhering to the conventions listed here can result in larger Web pages. The source code for your scripts will grow larger through the comments and as a result, so will your Web pages. However, in most cases, this additional overhead is very insignificant. It's also true that following conventions might take a little more time in the short run to initially write your programs. This time is more than saved by the improvements in development, debugging, and code maintenance that come about through the use of the conventions. It's also true that using conventions makes you or some of the programmers you work with feel constrained. This is another price that is worth paying if you care about efficient software development and developing the best program possible.

The benefits of standards and conventions are clear and overwhelming in the software industry. Good style and use of conventions pays off in many ways. For example, the use of good, descriptive variable names and procedure names often makes the code very readable in itself and lessens the need for many lines of comments. A more readable program can end up producing many benefits. Code can be easier to debug, maintain, and even originally design. As a result, the end product you provide on the Web for the user of your Web pages and scripts is better.

Q&A

QIf you will be the only one using your scripts, is there any advantage to using standards and conventions?
AYes, there certainly is. Adhering to standards and conventions can help you even at the initial script development time. It forces you to think through and document your code, procedures, and variables to a greater degree. This can lead to better design and implementation. It can be a great help in debugging when you must traverse through your code to track down problems. If you have to return to your code in the future, you'll have a much easier time if it has been written to standards and conventions. It is amazing how quickly a developer can forget programs that he has written a few months back!
QWhich procedure name is better for a procedure that converts inches to centimeters? Is it inchtoc or ConvertInchesToCm? Is it better to have a shorter name to save keystrokes?
AConvertInchesToCm is a much better procedure name. It is far more descriptive and therefore will be easier to maintain. The few extra bytes this name will cost you will probably not have any noticeable impact on your end user if your script is an average size.
QSuppose you have a text box that collects an age from the user. Is objAge a good name for that text box?
ANo, it is not. If you glance at the name of that object, the type of the object is not apparent. A better name would be txtAge. Then, it is clear that the object is type text.

Workshop

View the sample scripts from Microsoft on the World Wide Web. Take a look at their standards and conventions. (You can find all this information at http://www.microsoft.com/vbscript.) Document your own standards and conventions based on what you see there, what you've read today, and what you feel is appropriate. Document an approach that is good for you and your workplace. In what areas do you deviate from Microsoft and this book? Do you think the industry standard approach will be similar?

Quiz

Note
Refer to Appendix C, "Answers to Quiz Questions," for the answers to these questions.

  1. Observe the following program. Its purpose is to accept an age and present one message if the age indicates that the user is in Generation X. Otherwise, it will present a different message. If the age is invalid or hasn't been supplied yet, the user should receive appropriate feedback. Take the following segment and change the variable names and indentation to make it more readable.
  2. nm = info.value
    If IsNumeric(nm) then
    if nm < x then
    msgbox "Dude, prepare to surf!"
    else
    msgbox "Welcome - Prepare to enter our Web page"
    End if
    Elsif nm = "unknown" then
    msgbox="you must supply an age to proceed"
    Else
    msgbox "please supply a valid age"
    End if
  3. Take the following two scripts and merge them into one script:
<script Language="VBScript" FOR="lblFeedback" event=click>
msgbox "Feedback label has been clicked"
</script>

...html definitions appear here...

<script Language="VBS" FOR=cmdCalculate"event=OnClick>
msgbox "Button has been clicked"
</script>