Using Constants


Variables are values that can change. We give them a name, and then we can read to and write from the value that they hold. Literals are values that we directly type into our program code, like "Hello", 12.3, or #1/3/2003#. Of course, these values can't change while the program is running – they can only change if a programmer edits the code.

Constants are named values that cannot change during the running of a program. They are declared in a similar way to variables, but they use the word Const instead of Dim – and they must always be assigned a value when they are declared. Here's an example:

 Const pi As Single = 3.14159265358979 

It's clear why this would be useful. If we need to use the value of pi several times in our program, we can now refer to it by a short name – pi. Skillful use of constants can also make code easier to understand. Although most programmers would know that 3.14159265358979 is an approximation of pi, and is unlikely to mean anything else, a number like 7 could mean lots of things. Days in the week? Colors in the rainbow? Dwarves? Without analyzing the code, it would be impossible to tell. Using constants, it becomes much easier:

 Const numberOfDwarves = 7 

From then on, we can use the constant instead of the number itself. Of course, in this case the name is longer than the value so we lose some initial coding time, but it's usually worth the extra effort.

The real value of constants, though, is that they make code much easier to maintain. If disaster strikes and we're left with only six dwarves, or we decide that our approximation of pi needs to be more accurate, we only need to make the change once – in the constant declaration. Everywhere that uses the constant will be updated automatically.

These are the main reasons for using constants. They are simple and there isn't really much of consequence to say about them, but they are very useful.




Beginning Dynamic Websites with ASP. NET Web Matrix
Beginning Dynamic Websites: with ASP.NET Web Matrix (Programmer to Programmer)
ISBN: 0764543741
EAN: 2147483647
Year: 2003
Pages: 141

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net