Checking Value Types Before Use

VBScript is a "weakly-typed" programming language. This means that you can create, use, and access data values without initially declaring their types. However, certain operations can be performed only on values of a specific type. Therefore, it is important to check the type of the data before performing any operations on them.

Values of different types behave differently in different statements. Object value behavior is even more unpredictable because the behavior depends on the object's implementation. For example, the object in the call <entity>_CanDelete(Entity) can either be text or a subject node.

Recommendations

To avoid unpredictable results:

  • Check value types before use, especially for object types. When checking an object type, also check that the object has the properties you access.

  • Note: In the examples provided in this section, only object types are checked before use.

  • Assume as little as possible—do not assume that a value is of a certain type. Write scripts that can handle all possibilities by using Else statements and Select Case statements.

  • Always check parameter types before use with various VBScript functions, such as IsArray, IsDate, IsNull, IsEmpty, IsNumeric, and IsObject.

  • Do not assume an object's default property is of a specific type; the type can vary from object to object.

  • Use VBScript built-in conversion functions to achieve a degree of type safety.

  • When working with objects, check that the value you receive is neither Null or Empty by calling the IsNull and IsEmpty functions.

Example: For the purposes of the following examples, assume the field values are declared as in the table below.

Field Values

Type

Bug_Fields["BG_BUG_ID"].Value

Integer

Bug_Fields["BG_SUMMARY"].Value

String

Bug_Fields["BG_SUBJECT"].Value

Object implementing the ISysTreeNode interface

In the following example, statement usage is correct. The integer is converted to a string.

If Bug_Fields["BG_BUG_ID"].Value = "10" Then...

In the following example, statement usage is correct. The strings are comparable.

If Bug_Fields["BG_SUMMARY"].Value = "some text" Then...

In the following example, statement usage is incorrect. This code can work only when the value of BG_SUBJECT field is neither Empty or Null. VBScript also assumes that this objects's default value (meaning, the default property) is either of string type or is comparable with the string type, which is not always the case.

If Bug_Fields["BG_SUBJECT"].Value = "My Tests" Then...