Functions and Subroutines in ASP


As developers, we should endeavour to make our lives easier wherever possible... no one wants to re-invent the wheel after all.

Functions and Subroutines exist to not only save us time, but to bring power to our ASP.

They are just another way of encapsulating code, but have a lot more functionality than just 'saving some code for later'.

First, let's look at Functions... Imagine a balloon salesman in the street. We've all seen them they require one piece of information when you buy a balloon, the colour.
Let say we asked for a red balloon... The balloon salesman armed with this 'information' then does a pretty basic action... he hands you the balloon. The balloon you received is a direct result of the information you gave the balloon seller.

Functions are just the same... they return to you a value based on the information you provided. Lets look at an example Function: -

<%
Function getBalloon(strColour)
Dim Tempstr
strColour = lcase(strColour) 'This converts the value lowercase.
Select Case strColour
Case "red" Tempstr = "Here is your red balloon"
Case "yellow" Tempstr = "Here is your yellow balloon"
Case "green" Tempstr = "Here is your green balloon"
Case "blue" Tempstr = "Here is your blue balloon"
Case Else Tempstr = "Sorry, we have sold out of that Colour"
End Select
getBalloon = Tempstr
End Function
%>

A Function is passed some information. The information we pass a Function, is known as an 'argument'. The information we get back from a Function is known as the 'return value'. Whilst a Function can have many arguments, it can only have one return value.

Let us look at one more example: -

<%
Function calcTax(amount, taxrate)
Dim Tempvar
Tempvar = amount * (taxrate / 100)
CalcTax = Round(Tempvar, 2) 'round the result to 2 decimal places
End Function
%>

Again, another basic example. We should notice this time that the Function accepts two arguments.

By now, we have some idea of how to write a Function. How do we use one?
Let me show you now how we can use the calcTax example.

<%
shoppingbill=goodsTotal + calcTax(goodsTotal,17.5)
Response.Write "Your shopping came to £" & goodsTotal
Response.Write "
VAT amount = £" & calcTax(goodsTotal)
Response.Write "Total Amount Due = £" & shoppingbill
%>

Above you see the example function in action... easy huh!

I have tried to make understanding Functions as easy as possible... Understanding a Subroutine (Sub) is now going to be easy for you. Imagine a block of code that performed some instructions based on information you gave it...
Sounds very much like a function, doesn?t it? Well this time, we do not get anything back. A sub does NOT pass back information it just uses the data we give it for some purpose.

I will use only one example of a Sub, and in the same example make use of the sub: -

<%
Sub Bday(strName, intAge)
Response.Write "Happy Birthday " & Name
Response.Write ", You are " & intAge & " years old today"
End Sub

'now, call the sub
bDay "Joe",26
%>

The above Sub, demonstrates my point. We put something in, it performs an action (in this case writing to the screen), but nothing is returned to us in the code. One thing that REALLY IS important when using a sub, is that we do not put brackets around the arguments... Because we do not have a return value we do not need brackets and in this case, if we try we will get an error.

Well, that just about concludes this article. We should by now be writing efficient code with the use of Functions and Subs. Don?t forget that if you use your functions and subs in multiple pages then you should really store them within include files for reasons of easy maintenance and better performance.


More Resources

Unable to open RSS Feed $XMLfilename with error HTTP ERROR: 404, exiting

More Web Development Information:

Related Articles


9 Simple Steps to Create a Background Tiled Image Branded with Your Name
You have seen those web pages where they have the name of the Name Web repeated over over over in square tiles as the background. Now by following these 9 Simple steps you too can create a web page Branded with your Name, or Company Name.
Web Design for the Professional Magician Part I - Selecting the Perfect Domain Name
Selecting the Perfect Domain NameThe first issue I have with magician web sites is the improper use of domain names. Examine the following list of URLs and select the most professional one:www.
Selecting a Web Content Management Product
So you want to take a look at a real Web Content Management (WCM) product. How do you go about evaluating all the different products and vendors? What should you be looking for in a WCM package? Is it better to build your own, buy or use Open Source?The best way to answer this question is to compare the products on an apples to apples basis.
Lead Generation How to -- 10 Tips On Generating More Internet Sales Leads
Many millions of dollars are being wasted on promoting and sending traffic to ineffective lead generation websites. Here are my top 10 tips to make your site generate more leads for you and your company.
You May Be Losing Valuable Traffic - And Not Even Know It!
Here's something you may never have thought of before:If I were to type your domain name?http://www.yourdomain.
Websites for Writers - Why You Need One and How to Get Started Today
It may seem like the publishing industry's equivalent of Beanie Baby madness- everyone is talking about writer's websites. Freelancers and authors everywhere are jumping on the bandwagon, publishing sites to promote themselves and their work.
Why Every Small Business Owner Needs Two Websites
Every small business owner knows that they need a website, right? Well the truth is what they really need is at least two websites.One website that is specific to their business, product, service, name, etc.
If You Build It, They Will Come?
Building a new website can be a lengthy task. From scratch to the client's specification and then implement additional features and/or changes the client usually has.
MySQL Database Handling in PHP
Most interactive websites nowadays require data to be presented dynamically and interactively based on input from the user. For example, a customer may need to log into a retail website to check his purchasing history.
Achieving Differentiation With Your Website
Internet Marketing is not a miracle marketing strategy - competition still exists and you need to have a unique approach with regards to:Web DesignJust as in the "real world", where your brand needs to have a unique look and feel about it, so does your website. You won't have much luck finding a web design template that is consistent with your corporate identity.
12 Tips To Great Websites
Why do some sites succeed while the vast majority of others fail? More and more website owners are asking themselves these questions. The answers are often more obvious than you may think.
Have You Got Your Ear To The Ground Or Your Head In The Sand?
What happened on your website yesterday? What about last week or last month? How about in the past hour? How many visitors come to your website as a result of using a search engine? How long do people stay on your website for on average? Which pages do your visitors go to?If you don't know the answer to some or all of these questions you are effectively operating a website blind.This is like riding a bike blindfolded and expecting to arrive at the right destination.
Revealing the Firefox Secret Used by Top Web Developers and Power-Browsers
Profiles are one of the best kept secrets around regarding Mozilla Firefox (my browser of choice).In the role of web site designer, I find it useful to have Firefox set up with various Extensions for helping test compliance, keep track of Google Adsense earnings, checking PageRank and Alexa rating, etc.
Benefits Of An Accessible Website: Part 1 - Increase In Reach
The DDA (Disability Discrimination Act) states that service providers must not discriminate against disabled people. A website is regarded as a service and therefore falls under this law, and as such must be made accessible to everyone.
Why to Have a Website for Your Company
After having decided to start a business, the next thing that arrives in your mind is How to market the Product/Service? How to create a brand? How to recruit people? How & where to advertise? etc? Next is creating departments like Marketing, Operations, Advertising, Branding and Human Resource. You need some way to represent each department?For example Human Resource needs a way to represent the company to hire talents, marketing team needs someway to represent products/services, branding team needs a way to represent the company overall.
PHP & Account Activation
When a user signs up at your website, you may want to verify their email address so you aren't getting bogus accounts in your database. A few lines of code can send an email to the address specified, containing a welcome greeting and link to activate their account.
Maximizing ROI via Web Site Traffic Analysis
We are clearly well past the innocent "golden age" of the Internet - Darwinian economics have become the order of the day today. Any company worth their salt must maintain a web site as an information resource and/or to generate incremental ecommerce revenue.
What is SQL?
What is SQL? SQL stands for Structured Query Language and is the lingua franca in the database world. SQL is a standard that is used by all database vendors and programmers to define, extract and access the information that is stored in databases.
What Hosting Companies Dont Tell You, Could Hurt You?
Did you know that hosting companies overcrowd their servers despite all the issues caused by servers running hundreds of accounts? Are you aware of what happens if your website is hosted on a server that's overcrowded? You're probably thinking to yourself, "what do you mean overcrowd their servers?" Overcrowded servers mean big money for your hosting company, but also big problems for your website.Hosting companies are willing to sacrifice the success of your website in order to build their own profit.
Ecommerce for Beginners
Like most average persons, I wanted some extra money to supplement my regular income. I had considered a part time second job at times, but hated that option because it would take me away from the family, make me more tired and probably just pay minimum wage.