Page

5.5.2- Functions

  by NT Community Manager.
Last Updated  by Jim Minatel.  

PublicCategorized as 05. ASP Control Structures.

Not tagged.
<< 5.5.1- ProceduresChapter55.5.3- Summary of Reusing Code >>

Functions

Functions are written in a similar way to procedures, but with several special characteristics that handle the returning of information. There are five ideas to master for writing and using functions.

 

First, when you write a function you use Function (instead of Sub) on the first line and End Function (instead of End Sub) on the last line. The naming rules of functions are the same as for procedures: start with a letter, no spaces, and avoid symbols.

 

In the next few paragraphs we will build a function to calculate the due date of a library book (two weeks after the check-out date). The start and end of the function will look like this:

 

<%

Function FindDueDate()

...

lines of code

...

End Function

%>

 

The function usually receives some information from your main code in the form of a parameter (subprocedures can also receive information from parameters in the same way, only they can't return the values directly). This information is passed to the variable that you have named in the parenthesis following the function's name. You do not have to declare this variable using Dim – it is available for use automatically. For example, in our DueDate function we would expect to receive the checkout date from the main body of the code – this would give the due date function the starting point for its calculations. So now our code looks like this:

 

<%

Function FindDueDate(varCheckOutDate)

...

lines of code, some of which can use the variable varCheckOutDate

...

End Function

%>

 

Once the function has done its calculation, it has to report the result back to the VBScript engine. The VBScript engine processes whatever value is assigned to the name of the function. This is a little tricky for most beginners. Not only do you have available the variable which passed the data into the function (varCheckOutDate); there is also a variable (usable only within this function) that is automatically created with the name of the function, in this case FindDueDate. Whatever value is stuffed in that variable will be is sent back to the to the VBScript engine when the function is finished. For example:

 

<%

Function FindDueDate(varCheckOutDate)

FindDueDate = varCheckOutDate + 14

End Function

%>

The fourth concept is easy: how to use a function. You can call a function by just typing the name of the function followed by double parenthesis (we'll discuss the contents of these parentheses in a moment). You can then assign a variable to the return value of the variable as we do below:

 

<%

varOut = Date()

varDueDate = FindDueDate(varOut)

Response.Write "Your books are due on " & varDueDate

%>

 

varDueDate here contains the value returned by the calculations in our function. By assigning the value to this variable, we are running the function. The last idea is how to send the information from your main body of code to the function – in our case, the check out date of the book. We put whatever data we want to send to the function in the parenthesis. For example:

 

<%

checkoutDate = date()

varDueDate = FindDueDate(checkoutDate)

Response.Write "Your books are due on " & varDueDate

%>

 

And so we get the final product; VBScript code that creates a function, and then some ASP code which outputs the values that the VBScript function returns to ASP.

 

<HTML>

<HEAD>

<TITLE>Sample Function Page</TITLE>

</HEAD>

<BODY>

<%

Function FindDueDate(varCheckOutDate)

FindDueDate = varCheckOutDate + 14

End Function

%>

<H2>Thank you<BR>

for using the On-Line Library.</H2>

<%

checkoutDate = date()

varDueDate = FindDueDate(checkoutDate)

Response.Write "Your books are checked OUT on " & checkoutdate

Response.Write "<BR>Your books are due on " & varDueDate

%>

 

</BODY>

</HTML>

Common Errors when Writing Functions

  • Forgetting that functions, except in special circumstances, can only return one answer.
  • When using a function you must pass it the data it expects to receive. Sending a date when the function expects a price would hinder the function in carrying out its job
  • The answer that the function will provide the main code must be assigned to a variable that is named the same as the function name.

 

So now we're ready to look at an example.

Try It Out – Function to Calculate Expenses

Your colleagues come to hear a seminar in your city that you provide once per month. They can attend for two, four or six days. They need a rough idea of how much they will be charged for travel, and per diem. Everyone gets $75 a day for food. Some people like to stay in the city (hotel is $175 per night) while others prefer to stay in the suburbs ($85 per night). If they stay in the city, it costs $85 for transport to and from the airport. If they stay in the suburbs, they rent a car for $45 per day. Your task is to design a form that asks for the visitor's preference (a hotel in the city or in a suburb) and then creates a response page that gives them an estimate of their trip cost if they stay for two, four or six days of the seminar.

 

1.    Rouse your web page editor and type in the following:

<HTML>

<HEAD>

<TITLE>Function Form</TITLE>

</HEAD>

<BODY>

<H2>Cost Calculator for<BR>

Attendance at Corporate Conference</H2>

Please provide the following information so we can estimate your

local costs while attending the conference

 

<FORM ACTION = "FunctionResponse.asp" METHOD = post>

Please select your preference in location: <BR>

 

<SELECT NAME="location">

<OPTION VALUE="city">City</OPTION>

<OPTION VALUE="suburb">Suburb</OPTION>

</SELECT>

 

<BR><BR>

<INPUT TYPE = submit>

<INPUT TYPE = reset>

</FORM>

 

</BODY>

</HTML>

2.    Save it as FunctionForm.asp in your BegASPFiles directory.

3.    Now, create a new web page with the following code:

<HTML>

<HEAD>

<TITLE>Function Response</TITLE>

</HEAD>

<BODY>

<%

Function CityCost(NumberDays)

varHotelTotal = NumberDays*175

varMealsTotal = NumberDays*75

varAirportTransport = 85

CityCost = varHotelTotal+varMealsTotal+varAirportTransport

End Function

 

Function SuburbCost(NumberDays)

varHotelTotal = NumberDays*85

varCarTotal = NumberDays*45

varMealsTotal = NumberDays*75

SuburbCost = varHotelTotal+varMealsTotal + varCarTotal

End Function

 

varLocation=Request.Form("location")

%>

<H3>You have chosen the hotel in the <%=varLocation%>.<BR>

your estimated costs for this seminar will be:</H3>

<%

Select Case (varLocation)

Case "city"

varCost = CityCost(2)

Response.Write "The two day course will cost $" & varCost & "<br>"

varCost = CityCost(4)

Response.Write "The four day course will cost $" & varCost & "<br>"

varCost = CityCost(6)

Response.Write "The six day course will cost $" & varCost & "<br>"

Case "suburb"

varCost = SuburbCost(2)

Response.Write "The two day course will cost $" & varCost & "<br>"

varCost = SuburbCost(4)

Response.Write "The four day course will cost $" & varCost & "<br>"

varCost = SuburbCost(6)

Response.Write "The six day course will cost $" & varCost & "<br>"

End Select

%>

</BODY>

</HTML>

 

4.    Save it as FunctionResponse.asp in the usual directory.

5.    If you start up your web browser and run the FunctionForm.asp form page, you'll see the following.

Chapter5_image011

 

6.    If you select City and press Submit Query, you'll see the following information.

Chapter5_image012

How It Works

The two functions that perform our calculations are relatively straightforward.

 

Function CityCost(NumberDays)

varHotelTotal = NumberDays*175

varMealsTotal = NumberDays*75

varAirportTransport = 85

CityCost = varHotelTotal+varMealsTotal+varAirportTransport

End Function

 

The first function CityCost assumes that the hotel costs 175 dollars a day. So it takes the number of days supplied by the user, multiplies them by 175 and the stores them in the variant varHotelTotal. It does the same for Meals assume that the meals cost 75 dollars a day. The cost of air transport is a one off and costed at 85 dollars. Then the variable CityCost is created, adding the three values generated previously altogether. This is the value returned by the function. The function that calculates the cost by suburb works in the same way, just applying different prices.

 

Function SuburbCost(NumberDays)

varHotelTotal = NumberDays*85

varCarTotal = NumberDays*45

varMealsTotal = NumberDays*75

SuburbCost = varHotelTotal+varMealsTotal

End Function

 

We then detect whether the hotel is in the city of the suburbs using the Select Case statement. For the City, we then call the CityCost function, and store the value returned by the CityCost function. We then multiply the result returned by the CityCost function by 2, 4 and 6 respectively for the 2, 4 and 6 day courses:

 

Select Case (varLocation)

Case "city"

varCost = CityCost(2)

Response.Write "The two day course will cost $" & varCost & "<br>"

varCost = CityCost(4)

Response.Write "The four day course will cost $" & varCost & "<br>"

varCost = CityCost(6)

Response.Write "The six day course will cost $" & varCost & "<br>"

 

We do the same for the suburbs, displaying the result for the 2, 4 and 6 day courses.

 

Case "suburb"

varCost = SuburbCost(2)

Response.Write "The two day course will cost $" & varCost & "<br>"

varCost = SuburbCost(4)

Response.Write "The four day course will cost $" & varCost & "<br>"

varCost = SuburbCost(6)

Response.Write "The six day course will cost $" & varCost & "<br>"

 

Improvement to our Functions

We can live without the intermediate variable in our functions. The longer way we used is shown below first:

 

Select Case varLocation

Case "city"

varCost = CityCost(2)

Response.Write "The two day course will cost $" & varCost & "<BR>"

 

A faster technique is to directly write the function into the concatenation:

 

Select Case varLocation

Case "city"

Response.Write "The two day course will cost $" & CityCost(2) & "<br>"

<< 5.5.1- ProceduresChapter55.5.3- Summary of Reusing Code >>

Copyright © 2003 by Wiley Publishing, Inc.

Powered by Near-TimeTerms of Services | Privacy Policy | Security Policy |