Monday 26 September 2011

ASP: call functions and subroutines

   


With ASP, one of the main features we do like a lot is the possibility of creating procedures. There are two types of procedures: sub and functions.
Subroutines have a specific syntax:
<%
sub sub_name()
... ...
end sub
%>
and they don't output a result.

On the other hand, functions have the same syntax, but they output a result:
<%
function func_name()
... ...
end function
%>
Let's see how they work!


Examples
Let's create two simple examples: one subroutine and a function.
In the following snippet, we are using a subroutine in order to sum two values:
<%
sub sub_sum(val1,val2)
response.write (val1+val2)
end sub
%>
As you can see, we used the response.write to output the resulting sum.
We can obtain the same result with a function:
<%
function func_sum(val1,val2)
func_sum = (val1+val2)
end function
%>
In the above case, the function is returning the result of the sum.

Calling a sub and a function
To call the sub_sum, we need to do the following:
<%
call sub_sum(1,1)
%>
which will give us the result (2).
To call the func_sum, we do the following
<%
response.write (func_sum(1,1))
%>
which will produce the same result (2).

Differences? One and important!
You might wonder why we should use subroutines instead of functions and viceversa. The difference is very little but quite important. Infact, the point is that functions directly return the result. That means a function is completely independent and can be used in different situation. An example: let's say we want to sum two values in different parts of our document, but in a particular situation, we need to sum the two values and then divide it by 2. We can still use the func_sum function, and just "customize" the result in that occasion:
<%
response.write (func_sum(1,1)/2)
%>
That wouldn't work with a sub. To be more clear, we could have used a subroutine but the way to do it would have been more complicated and time consuming, while the function works perfectly.

I hope you've found the explanation useful.

0 thoughts:

Post a Comment

Comments are moderated. I apologize if I don't publish comments immediately.

However, I do answer to all the comments.