In the all too brief moments of down time between
projects I like to explore. Lately I've been exploring VBScript classes and have
decided to prepare a series of articles which will be presented here on ASP 101
to see if I can help shed
a little light on the topic. Don't expect a dissertation on Object Oriented Programming and Design,
I'm no expert in the field. If you're interested in that topic, you will find quite a few books available at
your favorite online book seller's site, or heaven forbid, out amongst the people
at a "real" bookstore. They still exist don't they?
The concept of classes/objects can seem very confusing
until that light goes off and you "get it". My advice: Don't sweat the
details. Use and study them, when they start to make even a little sense go
ahead and try to write some. You WILL make mistakes along the way, as long as you learn from the mistakes
you have lost nothing!
Required tools: A windows machine running either PWS or IIS. The latest scripting libraries,
which are automatically installed on your machine if you installed IE5 or you can download them
from the Microsoft Scripting Site . An html/vbscript editor of some type ... use NotePad if it makes you feel tough/cool/macho/whatever or it's all you
have, I prefer to use Visual Interdev 6 myself.
Are you ready? Cool! Let's dig in and start
looking at some code.
The class that we will be developing in this first article is called cRandom. It's usefulness
may be somewhat limited, but the class itself is of sufficient size to be a good practical example
of developing a basic class.
cRandom is a
wrapper class that seeds the
random number generator and has member functions for
returning a ranged random integer as well as returning an array of user defined size, populated with ranged random integers, with or
without duplicate values. Not very thrilling, but I've used the class in various prototype stages of some development
projects.
The first step in
the process is to create a new asp page.
Call it random.asp or a name of your choice, it really doesn't matter. The cRandom
class and some test code are all going to be embedded in the same .asp file
for this example. In "The Real World" you'll want to store all of
your reusable classes in seperate server side include files. Some people like to use
the .inc extension for includes, I typically leave them as .asp files and
just delete everything from the page except the code. Leaving the .asp extension on the file helps Visual Interdev know what to do as far as syntax
highlighting is concerned. Syntax highlighting and Intellisense are good things.
Have you created your ASP file? Excellent! Now go up to
the very first line of the page and define the default scripting language as
VBScript (Interdev does this for you automatically based on your language
settings) and right after that
you had BETTER put in
an option explicit tag. If you won't declare option explicit, I ask that you please leave now and never set eyes
on my articles again. ALL GOOD BOYS AND GIRLS USE OPTION EXPLICIT. Say that a few times so
it sinks in! The first two lines of your page should look like the following:
<%@ Language=VBScript %>
<% option explicit %>
Why use option explicit? It forces you to declare your
variables before you use them. Think about VBScript for a second, it is untyped,
not case sensitive and you can just start using a variable wherever you want if
you don't declare option explicit. When you start developing REALLY advanced scripted
pages you'll need all the help you can get in
keeping your code organized. There is nothing worse than some undeclared variable floating around
in global scope. Imagine a team of programmers working together on an asp page that
has 12 different server side includes. Now, imagine everyone with a variable
named 'i' or 'counter' in global scope. Things can quickly get out of hand on large projects. Enforce good coding standards on yourself
and others within your team.
Next we need
to name our class. This is another time when good standards will pay dividends
in the long run. All of VBScript's class, variable, function and subroutine names, as well
as those that you define, exist in a single name space. You'll
want to make sure that the names you choose aren't going to "step" on any others. Communication and good standards are once again
essential elements in YOUR success!
Classes have
the added side effect of hiding or encapsulating all
of their member variables, methods and properties. What this means is that
you can have two seperate classes, both containing functions, subroutines and variables with the same names. This simple fact alone can alleviate almost
all global name space issues!
My class is named cRandom, the small
leading 'c' is obviously meant to differentiate
it as a class, follow whatever naming convention you are most comfortable with. Make a choice and stick with it. We will begin
the class definition like this:
<%
' Begin the definition with the class keyword, followed by the
class name.
class
cRandom
'
Class_Initialize() is one of the two possible events that you can
handle in
' the lifetime
of a VBScript class, Class_Terminate() being the other. We need to
' seed the random number
generator by calling Randomize, the Initialize() event
' seems like a
logical place to handle this task.
private
sub
Class_Initialize()
Randomize
end
sub
' The
Class_Terminate() event is where we would handle any clean up
tasks
' required of the
class. Nothing needs to be done in regards to clean up for this
' class so we will
leave the Class_Terminate() event handler
empty.
private
sub
Class_Terminate()
end
sub
end
class
%>
Public and Private are essential keywords in the development
of a class. They allow you to show or
hide methods
(functions and subroutines) and properties (typically variables that
are accessed via properties or declared as public) within a class structure. This is
often called data hiding or encapsulation; it helps ensure that consumers of the class can't get
access to sensitive internal methods or properties. We will delve much more deeply
into this topic in future articles. The Class_Initialize() and Class_Terminate() subroutines are actually
event handlers that are automatically excuted when the class is created and
destroyed, respectively. They should never be executed by a consumer of the
class, always make them private. Public visibility of methods and properties is the
default, for clarity I recommend that you DO NOT exploit that fact and always declare everything with either public
or private visibility.
Two public functions and we're through for the day! Make
sure you check the source file for more detailed comments. Here's the code (add it right
after the Class_Terminate() subroutine and before the end class statement).
public
function RangedRandom( lowerBound, upperBound )
' set the badValue flag to an initial
value of false
badValue = false
' loop through the array and check for the
existence of the value
for i = 0
to
UBound(tempArray)
if tempValue =
tempArray(i) then
badValue = true
exit for
end if
next
' check the value of the flag, if it's
false add the value to the array and increment
' the value of filledElements counter by
1
if badValue =
false then
tempArray(filledElements) = tempValue
filledElements = filledElements + 1
end if
else
' This is the case where the user doesn't
care about duplicate values in the array
' so we add the value to the array and
increment our counter
tempArray(filledElements) = tempValue
filledElements = filledElements + 1
end if
loop
' Return the array,
populated with random integers to the caller of the function
RangedRandomArray =
tempArray
end
function
That's it! Click here to see the test output for the cRandom
class and download the code.
What articles are planned next?
In the next installment we will delve into properties
and the use of let, set and get. Along the way
we will be developing a sortable array class that utilizes the Quicksort algorithm, a LIFO stack class, a FIFO Queue class, some database connectivity
and convenience classes and whatever else you can suggest or I can dream up. It should
be fun and I'm looking forward to it! When is probably the next
logical question to answer, my best answer is ... "I
have no idea". I have most of the classes written I just need to wrap them up
into nice little articles. Oh ... and we'll probably get into writing some cool classes
in Visual Basic 6 that will be wrapped up in ActiveX dll's. Visual Basic offers
substantially more power than is available in VBScript.
Questions, Comments, Suggestions
and Making Contact with the Author
First
off ... I'm a VERY busy, independent contract programmer. Independent means that
if I don't work, I don't get paid!
I need to keep my priorities pretty straight. Keeping that in mind, if you have long
or involved questions that would take significant time (more than about a
minute) for me to answer, you likely won't get an answer unless you feel like paying
my normal consulting rates at a one hour minimum! ;-) My best advice on most programming related questions is
to "try it" and see what happens. The worst that could happen is you'll crash your
machine. You will learn so much more from personal exploration than you will from
someone just handing you the answer. Learning is a quest that each of us
should spend as much time on as possible.
Other options for assistance include the forums on ASP 101, the VBScript
documentation
that is available online from Microsoft, various
books available for purchase and many of the other fine ASP related websites out
on the net. Seek and ye shall find.
Got an idea for an article on classes that you'd like
to see? Kind words or raging flames? Send me your thoughts. If you intend to
email and flame me for being too verbose, don't bother ... I'm well aware of the fact that I ramble on a bit excessively.
Thanks
for reading and I hope you enjoyed the article. Now get out there and write some reusable classes! Peace.