Home > ASP > Making User-Defined Functions in ASP

Making User-Defined Functions in ASP

Functions are generally used to perform same operations, or compute equations. For example, suppose that you need to get an average of some numbers. What do you have to do? Are you going to write the equations all the time? A good programmer has to find the shortest way to do works. So, if we always need to get average of numbers, we write a function that evaluates average of numbers instead of writing equations for each operation. That’s why, we need functions, and that’s why you have to know how to use functions.


A function works in two different ways. It can return a value or it can do just operations. If the function makes only operations, doesn’t return a value then it is called void function, else it is called avoid function.

We use function procedure to create functions in ASP.

1.1 ) Making Avoid Functions in ASP

Structure 1.0: Structure of an avoid function in ASP

1
2
3
4
5
6
7
8
9
<%
function FunctionName( arguments )

'…
'Operations
'…
FunctionName=value
end function
%>

Example 1.0: A function gives us a random security number between 100000 and 10000.

1
2
3
4
5
6
7
<%
Function GenerateCode()
          randomize
          the_number = int(rnd*99999)+10000
          GenerateCode= the_number
End Function
%>

There is another example for creating user-defined functions: Making uppercase each word or first letter of a sentence in ASP.

1.2 ) Making Void Functions in ASP

Structure 1.1: Structure of a void function in ASP.

1
2
3
4
5
6
7
8
9
<%
function FunctionName( arguments )

'…
'Operations
'…

end function
%>

Example 1.1: Let’s write a function that closes open database connections or recordsets.

1
2
3
4
5
6
7
<%
function CloseIt(objectname)
on error resume next
objectname.close
set objectname= nothing
on error goto 0
end function %>

That function closes a database connection or a recordset.

Usage of CloseIt() Function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<%
function CloseIt(objectname)
on error resume next
objectname.close
set objectname= nothing
on error goto 0
end function

set MyRs=Server.CreateObject("ADODB.RecordSet")
SQL="Select * from memiso_users"
MyRs.Open SQL,memiso_conn,1,3

'…
'Operations
'…

CloseIt(MyRs)
CloseIt(memiso_conn)
%>


Keep in mind, if you have to make same operations for many times, it is better to write a function for executing codes faster.

Bookmark and Share
eXTReMe Tracker