One of the nicest features of Active Server Pages is it's support for simple object-oriented programming (OOP). Creating object-oriented code makes your applications easier to read and easier to manage. In most cases, it will take a little bit more work than creating global methods and variables, but in the long run, it will more than make up for that effort.
Class Declaration
Let's look at an example of how to declare a class in ASP:
Class clsImaginary
Private mReal ' real part
Private mImag ' imaginary part
' Constructor for the class
Private Sub Class_Initialize
mReal = 0.0
mImag = 0.0
End Sub
' Destructor for the class
Private Sub Class_Terminate
' do cleanup code here
End Sub
' methods
Public Sub Initialize(vReal, vImag)
mReal = vReal
mImag = vImag
End Sub
Public Function Value
Value = mReal & "+" & mImag & "i"
End Function
' properties
Public Property Get Real
Real = mReal
End Property
Public Property Get Imag
Imag = mImag
End Property
End Class
This code contains the definition of a class encapsulated between the Class and the End Class keywords. It includes two private member variables, a constructor, a useless destructor, two methods and two properties. The order of sections doesn't matter at all except where readability is concerned. I prefer this ordering because it makes most declarations easy to find.
You will notice all elements within the class declaration contain a Private or Public access modifier. Private means that the method or variable can only be accessed with the class declaration (between the Class and End Class statements.) Public means that the method or variable can be accessed from either within the class or through the instance of a class (as we'll see later.)
Another thing you should take note of is that there can only be one constructor named Class_Initialize and it cannot take any arguments. This means I cannot create a constructor that takes a real and imaginary component to initialize the member variables. That is the reason I needed to create the Initialize method to seed the initial value for the real number.
The constructor method (which must be named Class_Initializej) will be invoked automatically when your class is created. Likewise the destructor (which must be named Class_Terminatej) will be invoked automatically when your class is destroyed. Our destructor method doesn't do anything because there is no need for it (so we could have just left this method out of the class declaration. A good use for a destructor is cleaning up resources that are in use such as a connection to a database or an open file handle.
The methods in the class declaration look just like global function declarations with the exception of the Public or Private modifiers. They behave exactly the same except that they must be invoked through the use of a class instance.
Within any of the method or property declarations, you still have access to all global methods and variables. The benefit of encapsulating them within a class is that you don't have to worry about name collisions. The class also creates it's own namespace allowing you to use short and simple names for your methods, properties and member variables.
Since classes are intended to be reusable pieces of code, it makes sense to place a class declaration or set of multiple class declarations within a separate file. Unlike languages like Java, there is no need to make the name of your file match your class name. This file can be included into your scripts that need to use the class. I usually create a base folder named lib that contains all of my include files.
Using a Class
An example of making use of a class is shown below:
Dim oImag
Set oImag = New clsImaginary
Response.Write "Before Initialization: "
Response.Write oImag.Value
Call oImag.Initialize(3.443, 1.43)
Response.Write "
After Initialization: "
Response.Write oImag.Value
As you can see in the example, the steps are:
- Declare a variable
- Set the variable to be an instance of the class by using the New keyword
- Invoke a method of the class by using the dot (.) operator
There is no need to explicitly destory an instance of a class unless you have a specific terminiator that you want to be invoked. In this case you can use the following code to destroy the class:
Set oImag = Nothing
Member Variables
Member variables are special variables that are encapsulated within your class declaration. They are not accessible outside of a class declaration unless you declare them with the Public modifier in which case they can only be accessed through a class instance.
I prefer to prefix my member variables with the letter "m", but you can use any naming convention you like. Previously, I used a letter to denote the value type being stored in the variable (ie: "s" for string, "n" for integer, "f" for float, "b" for boolean, "c" for char and "o" for object.)
When accessing member variables within a property or method, there is no need to use a this or similar keyword. These variables are simply accessed by using their variable name as shown in our example.
You cannot declare constant variables (using the Const keyword) within a class. One alternative would be to create a public member variable, but that would not really be a true constant because the value could be modified. A better option would be to create a property which only supports the Get method as shown below:
' constant value PI (as a property)
Public Property Get PI
PI = 3.1415926
End Property
Constructors
Constructors should always be declared as subroutines (using the Sub keyword.) Additionally, you should always declare your subroutines using the Private modifier since they will never be called directly using a class instance.
The use of a constructor and destructor declaration is totally optional. You can declare one or the other or neither if you choose. Most often, I use a constructor to initialize my member variables without a destructor.
Methods
Methods are the real workhorse of the class. They perform all the heavy lifting of the class. They are basically functions and subroutines that are encapsulated within the class declaration. By using a Public or Private access modifier, you can hide or expose the method to the outside world.
Because the method must be accessed via a class instance, the method name can be very short. When using procedure programming, you would have to prefix your function names with a module prefix such as imagValue(). Because the class declaration create a kind of namespace, we can use the shorter method name Value.
Consider not using too many arguments within your method declaration. It is better to keep your argument list the same and just add new member variables and properties to pass values to the member variable. This will allow you to create new versions of your class that are backwards compatiable with older code you have written.
Properties
Properties are used for accessing data within your class. They can be used for both reading and storing a data value. There are three different property types that can be defined:
- Get - Read a property value
- Let - Store a property value
- Set - Set a property value to an object instance
You will notice that there is only one property type for retrieving or reading a property value (Get). Because of this, you can use Get to return either a regular variable or an object instance. We've already seen in the previous example how the Property Get declaration works.
When declaring a Let or a Set property, you should only declare one argument which is used to pass the value or object instance you wish to assign. I typically use a variable named vValue but you can use whatever you like. An example of using Property Let is included below. Set works the same way except you change Let to Set and the value must be assigned using the Set keyword.
Instead of making a member variable public and letting anyone store any type of value, keeping it private allows you to control what type of data goes into a variable and what type of data is read out.
Take for instance, a variable that represents the month of a year. This should hold a value between 1 and 12. We would like to make sure that only these values can be stored in the variable. Here is what the code would look like to do this:
Class clsImaginary
Private mMonth ' month of the year
Private mImag ' imaginary part
' month property
Public Property Let TheMonth(vValue)
If IsNumeric(vValue) Then
If CInt(vValue) >= 1 And CInt(vValue) <= 12 Then
mMonth = CInt(vValue)
End If
End if
End Property
End Class
Summary
This article summarizes the object-oriented features of the Active Server Pages language. ASP provides a basic framework that allows us to create powerful classes without too much effort. Object-oriented language features in ASP include:
- Member variables
- Constructors and Desctructors
- Methods (functions and subroutines)
- Private and Public access modifiers
- Let, Get and Set properties
Object-oriented features not supported in ASP:
- Constructors with initializers
- Method overloading
- Member constants (property serves this purpose)
- Operator overloading
- Inheritance
- True namespaces
Use of classes in your applications will help you avoid name collisions and to encapsulate critical data and methods that should only be used within a class. By using properties instead of global subroutines, you can keep your function arguments the same while adding new properties to your class. This will help to keep your methods backwards compatible with older code.