Microsoft® Windows® 2000 Scripting Guide
« Previous | Next »
Many shorter scripts (those with fewer than 100 lines) are written without using any functions or procedures. Instead, the actions carried out by the script are performed in linear fashion in the main body of the script. This is the recommended way to write short scripts; needlessly wrapping code in a function that is called only once merely makes the script longer, more difficult to read, and harder to maintain.
When working with longer scripts, however, you should place your code in separate functions and procedures whenever possible, and for the following reasons:
Include files enable you to create scripting libraries, collections of code snippets that carry out particular tasks. For example, you might have code that parses command-line arguments. The next time you write a script that requires command-line arguments, you can write a single statement that calls the appropriate script in the code library. Writing the initial code as a function or procedure makes it easier to remove the code from the script itself, place it in a code library, and make it readily available to other scripts and script writers.
VBScript provides multiple ways to call functions and procedures. Some require parentheses around parameters; others do not. This is important, because improperly called functions and procedures can either result in errors within the script or, perhaps worse, cause subtle changes that affect the data returned by the script.
Valid ways of calling functions and procedures and passing parameters are shown in Table 18.5. For more information about passing parameters by value and by reference, see "VBScript Primer" in this book.
Table 18.5 Calling Functions and Procedures by Passing Parameters
Passing Mechanism | Syntax |
---|---|
By reference |
|
By value |
|
First parameter by reference, second parameter by value |
|
Note
Calling functions and procedures in multiple ways can lead to considerable confusion and errors within the script. For example, an error occurs if you use a syntax that inadvertently passes a parameter by value when you intend to pass it by reference (or vice versa). To prevent problems with function and procedure calls, explicitly indicate the passing mechanism when writing the function or procedure. For example, the function shown in the following script snippet makes it clear that the parameter is being passed by value:
Function ConvertToFahrenheit(ByVal sngDegreesCelsius) ConvertToFahrenheit = (sngDegreesCelsius * (9/5)) + 32 End Function
As a general rule, pass parameters by value rather than by reference. Passing a parameter by value ensures that your function will not inadvertently change the value of that parameter. This is especially important if the parameter is required elsewhere in the script.
Note
Send us your feedback | « Previous | Next » |