Monday, May 15, 2000

Programming Tips & Tricks #0002---Enforcing Variable Declaration in your VB program

Tips & Tricks #0002

In a previous article, I mentioned the importance of enforcing Variable Declaration in your Visual Basic program by ensuring that ‘Option Explicit’ is coded in the General Declarations Section of each module in your project.

Most high level programming languages force the developer to explicitly declare a variable before using it. Visual Basic is a notable exception. In fact, by default, VB’s installation leaves the Visual Basic environment in a state where variable declaration is NOT required.

After installing Visual Basic, immediately select Tools-Options and check ON

Require Variable Declaration

Selecting this option causes Visual Basic to insert this statement

Option Explicit

into the General Declarations Section of each module in your project. The result is that an attempt to refer to a variable in code without first declaring it results in a compiler error.

What’s the big deal, you might ask? Is there really a harm in leaving this option checked off? Suppose you use a variable in code that you haven't declared? Visual Basic is a programmer friendly language—won’t VB take care of it?

The answer is yes---VB will take care of it---but the price of a mistake on your part can be huge.

For instance, suppose you assign a value to a variable called sngUnitPrice like this…

sngUnitPrice = 13.48

and then later in your code you attempt to refer to this variable in a calculation, but accidentally refer to it by an incorrect name, for instance sngUnitCost (yes, it can happen!)

sngTotalPrice = sngUnitCost * m_intQuantity

You're expecting the program to come up with a valid price--instead, the result will be zero, since the value of the incorrectly named variable sngUnitCost is zero!

When you tell VB to enforce variable declaration, errors like this are caught at compile time---potentially preventing disastrous results form occurring.

No comments: