Re-usable code is a boon to developers. It's easy to manage, because it only needs to be written once; then, every time you want to do the same thing, you just call it up again. However, it does require a bit of thought and planning up front. John Puddinfoot walks us through several simple applications for re-usable code in ASP, focusing on functions.
Contributed by John Puddifoot Rating: / 269 December 21, 2004
As with every design decision, the choice to develop re-usable code is a matter of trade-off. Making the decision to develop re-usable code will help to produce more robust and maintainable solutions, but may require a little more time and thinking up front.
In many ways ASP is an unstructured language. The language itself does not constrain a developer to design something in a particular way, which again has its good points and its bad points. The emphasis is on the developer to apply hisr own style to the work. Functions provide developers with an option to produce code that can be used time and time again within a project and beyond, yet many ASP developers tend to shy away from using them extensively.
This article will introduce the basic concepts of functions within ASP, and we’ll go on to produce a very useful function to demonstrate the concept. To start us off, here's a very simple piece of work: doing some very basic maths to demonstrate that even with the simplest of coding tasks, functions have a real use.
Customer Spec: "Here’s the idea John, we have two values which we need to add together and display the result on the screen."
It’s a simple enough concept. We’ll take two numbers and add them together to create a result then display this to the screen. First we’ll do it the natural way. We’ll code it straight out – all two lines of code!
Ok, pretty simple – so let’s complicate this one with by wrapping it up in a function called "simplemaths." Let’s look at the function protocol first:
<% function simplemaths(var1, var2)
end function %>
We’ve created a function (which doesn’t actually do anything yet). It needs two input variables (var1 and var2). We would then use the following code to call the function if both of our variables equalled 3 and 2:
<% call simplemaths(3, 2) %>
Simple, right? All that we need now is to edit our function so that it actually does something! Just as the customer requested, the function will simply add our two values together and produce the result on screen.
<% 'Define our function function simplemaths(var1, var2) result=var1+var2 response.write result & "<br />" end function
'run the function call simplemaths(3, 2) %>
Note that var1 and var2 are the variable names within the function and not outside it. You could choose to use variables outside of the function too. To add 10 and 20 together using variables:
<% 'Define our function function simplemaths(var1, var2) result=var1+var2 response.write result & "<br />" end function
Customer Spec part 2: "Ok John, that’s great, now we need to do it for all of these numbers too…."
You suddenly need to work out the result of hundreds of sums. But because we have a function that does all of the dirty work (okay, perhaps it’s not that dirty) you only need to add one line of code per calculation:
<% function simplemaths(var1, var2) result=var1+var2 ' Add a new line to do the multiplication result=result*10 response.write result & "<br />" end function
So you’re happily coding away, putting the final sum together when the customer calls you again:
"Erm, I’ve just realized – I need you to multiply all of the numbers by ten before you write them to the screen! Sorry!"
If you had hundreds of individual calculations then that could be a big task. If you have one function that does it all, then it’s easy!
<% function simplemaths(var1, var2) result=var1+var2 ' Add a new line to do the multiplication result=result*10 response.write result & "<br />" end function
Pretty compelling, eh? So functions are the bee’s knees and re-usable, maintainable code will save us all. The functions that developers have as a resource act as the foundations for the applications that they produce and the ability to control these functions is a valuable one. The concept relies upon the fact that you and your code shouldn’t really have to worry about how to achieve the specific task – because after you’ve coded it once you never need to code it again. It’s a little black-box of code and all you need to know is how to use it (not how it works inside). This description is edging us gently towards the concepts of Object-Orientated (OO) Design and if you’d like to stick with me through the series of articles we’ll attempt to cover this in more detail – by developing more real-life examples and ideally code that we all can use and re-use!
The following function provides a real life example of a common ASP task. Customer Spec: "The job is to create a drop-down box on my webpage using values from my database table. The table is called tbl_fruit and lists different types of fruit. Take a look at the table below as an example. Oh yes, I might need the drop down to sit inside a form with other input fields."
fruit_id
fruit_name
1
Apple
2
Pear
3
Orange
The solution is to develop a function named "db_dropdown" which we’ll call in our script just as we did with the simplemaths function earlier.
The function will carry out the following tasks (which could be further broken down into more functions if we choose to do so):
Open a new HTML dropdown box definition
Query the database table using an open connection. (This opens a recordset object).
Create an option for each record in the recordset result in a single drop-down box
Close the recordset connection
Close the HTML dropdown box definition
<% function db_dropdown(dbconnection, tablename, bound_field, display_field) ' output the HTML code to initialise a drop-down box response.write "<select name='"&bound_field&"' id='"&bound_field&"'>"
' open recordset connection strSQL="SELECT " & bound_field & "," & display_field & " FROM " & tablename set xrs=server.createobject("adodb.recordset") xrs.open strSQL, dbconnection
do while not xrs.eof ' for each line record, write an option to the drop-down box response.write "<option value='"&xrs(0)& "'>"& xrs(1)& "</option>" xrs.movenext loop
'clear up the connections xrs.close set xrs=Nothing
' output the HTML code to close the drop-down box response.write "</select>" end function %>
That’s the function, ready to go. It might not be perfect yet, but because we only need to write it once and we’ll maintain it in one place we can perfect it later. It’s a good idea to keep all of your functions in one place. If you’re familiar with using "Include Files" that’s a great option – if not, then you have some more reading to do! Again it comes down to maintainability. If you have one copy of each of the functions kept in one central file it’s easy to update if necessary.
So now we need to call the function. There is a wealth of information on database connectivity techniques dotted all over the Web, but for the sake of simplicity we’ll assume we’ve got an MS Access database called "shop" stored in the same folder as the script. This is sufficient for initial learning but it is worth taking look at the alternatives available to you for your live site and the security implications of the options.
Here is the complete script. Simply paste this into an ASP file – and to test you’ll need that copy of the database as described above.
' close the db connection dbconn.close set dbconn=Nothing %> </form> </body> </html> <% function db_dropdown(dbconnection, tablename, bound_field, display_field)
' output the HTML code to initialise a drop-down box response.write "<select name='"&bound_field&"' id='"&bound_field&"'>"
' open recordset connection strSQL="SELECT " & bound_field & "," & display_field & " FROM " & tablename set xrs=server.createobject("adodb.recordset") xrs.open strSQL, dbconnection
do while not xrs.eof ' for each line record, write an option to the drop-down box response.write "<option value='"&xrs(0)&"'>"& xrs(1)&"</option>" xrs.movenext loop
'clear up the connections xrs.close set xrs=Nothing
' output the HTML code to close the drop-down box response.write "</select><br />" end function %>
Now every time that you need a drop-down box you simply have to call this function "db_dropdown". You may choose to place the Database Connection object inside this function or even another function. There are many ways this function can be developed further and that is the great benefit of the concept. The code may do exactly what you need it to do now, but in six months time you may decide that the results need to be sorted in alphabetical order, or that you want to add a default value to the function. With a bit of thinking you’ll be able to achieve this with an absolute minimum of work.