I normally work with ASP.NET, not Classic, but my current position has a legacy ASP application (poorly written) that I'm trying to refactor. I'm looking at modularizing the code and using OOP techniques - I have a sample class that sets a few basic properties of a Customer entity, and uses the ActiveRecord pattern to return an array of all of them.
When I try to iterate though the collection using a simple For Each loop, and display the object's properties, VBScript complains.
My code is as follows:
' Customer class
Class Customer
Private m_idCustomer ' As Integer
Private m_name ' As String
Private m_lastName ' As String
Public Function Create(id, name, lastName)
m_idCustomer = id
m_name = name
m_lastName = lastName
End Function
Public Property Get ID ' As Integer
ID = m_idCustomer
End Property
Public Property Get Name ' As String
Name = m_name
End Property
public property get LastName ' As String
LastName = m_lastName
end property
Public Function FindAll() ' As Array
Dim aryCustomers()
Set rs = DbManager.ExecuteStatement("SELECT TOP 10 idCustomer, name, lastName FROM customers")
If Not rs.EOF Then
ReDim aryCustomers(rs.RecordCount)
While Not rs.EOF
For i = 0 To (UBound(aryCustomers) - 1)
Set c = New Customer
Call c.Create(rs("idCustomer"), rs("name"), rs("lastName"))
Set aryCustomers(i) = c
rs.MoveNext
Next
Wend
End If
FindAll = aryCustomers
End Function
End Class
<!-- This is in the calling page -->
Set someCust = New Customer
custList = someCust.FindAll()
For Each cust In custList
Response.Write "ID: " & cust.ID & "<br />"
Response.Write "First Name: " & cust.Name & "<br />"
Response.Write "Last Name: " & cust.LastName & "<hr />"
Next
----
This seems to be pretty simple, and I'm not sure why VBScript is complaining. The exact error I get points to the "For Each cust In custList" line, with the specific error being "Object required: cust" - clearly, VBScript isn't setting cust to be a Customer object, and is trying to call a property on a String. However, I get it to work when I use a normal For..Next loop (e.g. "For i = 0 To UBound(custList) - 1"), and when I use custList(i) instead of cust. While it's not a big deal, I Prefer the For Each syntax; I think it's cleaner and more natural to use.
Can I do what I want to in VBScript, or am I stuck using For i = 0 To UBound(custList) - 1? As I said, I'm not really familiar with VBScript, but I'm trying to clean up the horrendous codebase I've "inherited" - the previous programmer didn't indent anything, used cryptic variable names, and made gratuitious use of On Error Resume Next to make sure that his code worked (in other words, if I remove it, the code dies with some nonsense error like calling a method on an item that hasn't been created yet, because it's created twenty lines further down the page).