Choosing a Script Construction

Microsoft® Windows® 2000 Scripting Guide

Although scripts often include an initialization section, a main body, and a set of functions and procedures, you can arrange those elements in different ways. As you might expect, some of these arrangements are better than others, depending on the length and complexity of the script. For example, scripts that span hundreds of lines and need to use the same code over and over benefit from a construction in which repeated code is placed in individual functions. By contrast, functions and procedures can needlessly complicate shorter scripts that perform only a single task. For example, placing the following code in a function does nothing to help the performance of the script and only makes a simple script much more complex:

Wscript.Echo AddTwoNumbers
Function AddTwoNumbers
    AddTwoNumbers=2+2
End Function

This same script can be written as follows:

Wscript.Echo 2+2

Table 18.4 lists advantages and disadvantages of several different scripting formats.

Table 18.4 Advantages and Disadvantages of Various Scripting Formats

Script Construction

Advantages

Disadvantages

Scripts that do not call any functions or procedures

  • Easiest way to write a script

  • Good choice for small scripts (less than 100 lines) that do not repeatedly call the same functions or procedures

  • Difficult to identify key components of the script

  • Can result in needless duplication if the same lines of code are used repeatedly

  • Difficult to create script libraries because there are no procedures in the script

Scripts that scatter functions and procedures throughout the script

  • None

  • Results in code that is extremely difficult to read and maintain

  • Not recommended under any circumstances

Scripts constructed as follows:

  1. Initialization section

  2. Main body of the script

  3. All functions and procedures

  • Easy to read and understand

  • Script logically organized

  • Requires readers to flip back and forth between the main body and called functions or procedures

  • Might not be needed in shorter scripts unless a function or procedure is called multiple times

Scripts constructed as follows:

  1. Initialization section

  2. All functions and procedures

  3. Main body of the script.

  • Makes it easy to identify the primary operations that are carried out by the script

  • Can be difficult to follow the scripting logic; anyone reading the script needs to search for the main body

Scripts constructed as follows:

  1. Initialization section

  2. A single statement calling the procedure Main (which contains the main body of the script)

  3. Remaining functions and procedures

  • Follows the formatting conventions used in many programming languages, including the Visual Basic .NET languages

  • Requires readers to flip back and forth between the main body and called functions or procedures