Friday, October 06, 2006

Passing Values out of a Subroutine in ASP

It's a known fact that most programmers (and most people in general) are lazy. In ASP, declaring variables is optional, so most programmers don't. I've gotten away from that and tend to do Option Explicit at the top of my page and then declare all my variables
<%
Option Explicit

Dim Var1, Var2, Var3
%>
I've found it makes it easier for me to debug my code.

If you do declare your variables, do it first thing at the top of the page for your global variables. If you use function or subroutine variables, you can declare those inside the subroutine of function in which you use them.

The main advantage of declaring variables is that it makes it easier to debug your code, because if you misspell a variable it will show up as undeclared. Declaring your variables has an added effect, usually unknown to beginning programmers.

Say you have a subroutine the figures out the values of something:
<%
Sub DoSomething
x = 1
y = 2
z = x + y
End Sub
%>
Now you would think the value of z would be accessible to the rest of the page, but it won't unless you've declared it as a global variable outside the subroutine. So if you try this:
<%
Call DoSomething
response.write(z)
%>
You won't see anything, because the value of z won't come out of the subroutine. You have to do it like this:
<%
Dim z

Call DoSomething
response.write(z)
%>
In this example, since z has been declared as a global variable, it will persist out of the function and be accessible to the rest of you code.

I remember practically pulling my hair out the first time I used a subroutine to concatenate a string and then couldn't get the string to print!

There is another way to accomplish this without using a script level Dim statement; you can declare the subroutine as Public.
<%
Public Sub DoSomething
x = 1
y = 2
z = x + y
End Sub
%>
So here are the rules summed up:
  • Variables in Private subroutines and functions are available only to that function or subroutine
  • Variables in Public subroutines and functions are available to the entire script
  • Variables declared at the script level are available to the entire script
  • Variables declared at the subroutein or function level are available only within that subroutine or function

No comments: