After reading this article, I would suggest you to read
ASP Tips to Improve Performance and StyleIf you are getting started programming Active Server Pages, there are a few standardized programming practices you can use to make your code more readable. If you are already an advanced Active Server programmer you will probable have many of your own.
Programming standards have been common practice in many programming languages for years. However, unlike most things in computer science there is more than one way to format your code, some better then others, and all controversial. We have written down our thoughts on Active Server page standards in the following article.
Use Hungarian notationHungarian notation is a standard in defining variables. To use Hungarian notation you add characters to the front of a variable where the characters define the data type. The benefit of using Hungarian notation is that at one glance of the variable, you should be able to interpret both the variables data type and purpose.
For example, suppose you have a variable 'Company'. The variable name of 'Company' can indicate a company name or a company id. You would have to look at how the variable is used or find the definition to know the data type. A better variable name is sCompanyName. The 's' indicates a string of characters and the 'CompanyName' indicates the information contained in the variable. If someone runs across 'sCompanyName' in your Active Server page they will know that it is a string.
This is probably trivial if you are the lone programmer with very little code in your library. Many code bases start out that way. But a successful piece of code will be passed around and be used my many programmers.
Put Request parameters into variables onceRequest parameters are those parameters that are passed from one web page to another in the form of:
Code:
http://www.myserver.com/page.html?Param1=XYZ&Param2=45
In the example about the Param1 and Param2 are the request parameters. Every time you retrieve a parameter's value from using the Request object, the request object has to retrieve that value. You should always have a location/function that grabs the parameter values. For example:
Code:
<%
sParam1=Request("Param1")
iParam2=Request("Param2")
%>
<HTML>
<BODY>
<%=sParam1%> : <%=iParam2%>
</BODY>
</HTML>
You gain performance by retrieving each variable only once and you know where to look for the code that retrieves that value. Secondly, if you change the param name in the request parameters, you only have to change the retrieval code once.
By retrieving it once in a single location, you can manipulate the data in any way that you need.
Use Option ExplicitBy adding the command:
Code:
OPTION EXPLICIT
on the very first Visual Basic line on the page you force a stricter coding style than the default. With Option Explicit specified, the programmer must Dim all variables before using them. This prevents programming errors like the following:
Code:
Dim cObject As int
cObjects=0
For Each Object in Collection
cObject=cObjects+1
Next Object
Notice that no matter how many Objects that there are in the collection coming out of the loop cObjects will be zero. This is because the programmer made a mistake and left of the 's' in the increment line. The code would execute without compiler error, however with
OPTION EXPLICT set a compiler error would happen.
The trade off is that you have to do more typing, declaring all the variables, but you produce cleaner code.
Put ASP delimiters at the left hand margin unless code is in lineWhen writing an ASP page, you use the <% and %> delimiters so the ASP compiler knows when to interpret your code versus displaying HTML code. You can mix ASP and HTML in one of two ways (or both at the same time).
When maintaining or debugging ASP pages, it is important to know where the HTML code is built and returned. If you have to scan the code for the delimiters, the process can become tedious. Always put ASP code delimiters to the far-left margin (the first example), unless the ASP code is inline with the HTML (the second example).
Use Include FilesWhen programming C or Visual Basic, knowing when to use a procedure to encapsulate code that is used again and again is a distinction that separates good from average programmers. In programming Active Server Pages, include files are the equivalent of procedures.
For Example, you have 50 Active Server Pages, which include a meta description for search engines.
You realize that you want to change the description after adding the correct line in all 50 pages. Now you have to go through and modify all 50 pages again.
You would only have to change the include file to change the meta description in all 50 pages. Many Sites rely heavily on include files for quick manipulation.
Some of the things that can be included are:
- Cookie Handling Functions
- Constent Variable declarations
- Footers
- Headers
- Repeated Text
Know when to use a Sub versus a FunctionThe Function has the ability of taking and returning parameters as well as a return value. A Sub has the ability to taking and returning parameters but does not have a return value.
A function should always be used if any error can happen inside the function. The first example is a routine that takes as a parameter a string of characters. The code inside the routine should check to see it the string of characters is "" or null before any processing. If the string is null then an error via the return value should be thrown.
If the routine requires absolutely no processing of global or local variables, then use a SUB. An example is an SUB that prints out the current date (using the Date() function) in HTML.
Leave plenty of white space and tabsIt's very easy to get into the habit of writing code quickly but not so quickly debugged or maintained. The expense of the project will be in maintenance and debugging. By adding white space and tabs to the code, you are ensuring a degree of logic and readability to your code. Most of the code written in this article uses standard practice white space and tabs and should be easy to read. By interweaving HTML and ASP code, it is twice as important to be able to quickly determine if the cause of your problem is due to HTML or ASP code.
Understand the difference between when to use global variables and when to pass variablesGlobal variables should be any information that is 'global' to the entire application. You may have a routine that always prints the page title (a global variable) in the <H1> tag. As long as that function is used to only print the page title, there is no reason to pass the parameters.
However, assume you have a function that prints out a result set from ADO. This result set can have a different title each time so the title should be passed in as a parameter.
More Recommendations- Use meaningful names for all your variables, functions, objects etc
- When modifying existing code or extending it may not be possible to use option explicit due to dependencies between the files. In those cases, try to make this possible and consult your team leader if the amount of work is significant or likely to impact your schedule of work.
- Use Local Variables in Subroutines and Functions.
Local variables are those declared within subroutines and functions. Within a function or subroutine, local variable access is faster than global variable access. Use of local variables also tends to make code cleaner and avoids data getting mixed. - Avoid re-dimensioning arrays.
- Use Response Buffering. This minimizes the amount of writes to the browser and thus improves overall performance. Each write has significant overhead. If some part of the page may take a long time consider using Response.Flush before very expensive operations.
- Use client side validation when possible but validate server side as well.
- Always validate input parameters before executing code. Make sure that if an input value is invalid it is handled appropriately.
- Copy individual values from collections into local variables, if you are going to reference the value more than once. This saves ASP from having to perform lookup processing in the collection for each and every reference.
- Don’t expect the ASP engine to clean up your objects. Always close then and set them to nothing as soon as possible. E.g. set objObject = nothing
- If you are going to loop through a long recordset, consider loading it into an array using the Recordset.GetRows method and close your recordset before you process it.
If not using arrays consider using a field reference if you are looping through many results (e.g. set objField = objRs(“fieldname”) ). Then reference with objField.value. You can also use indexes instead of field names but define the numeric values in variables. E.g. nField1 and then recordset(field1) - Minimize context switching. For readability and performance, try to minimize context switching between HTML and scripts. When possible, use a few large blocks of script on a page instead of several scattered fragments.
- Handle errors gracefully. Errors should be handled and appropriate user-friendly messages displayed. Don’t assume that things will execute correctly.
- Encapsulate your code. If you are going to have small include files with some functionality it makes more sense to encapsulate it and apply proper error handling to it.
- Think in terms of layers. Use VBScript classes to encapsulate business logic, database access and presentation tier when sensible.
- Limit the dependencies of objects and routines to their property and parameters. Avoid depending on global variables when possible or the QueryString and Form collections.
- Before you code, think what you want to achieve and what is the best way of doing.
- Always comment your code. Always specify dependencies in the code.
- If you modify existing code, add comments of what you modify and when.
- Organise and name your files meaningfully.
- Don’t abuse on nested code include files; it makes documentation and debugging more difficult.
- Be consistent in your coding.
- Always properly indent your code; it makes it more readable and easier to understand and debug.
- Test, test and test what you do.
- Do performance testing.
Original Source and Additional Resources