home navigator pointer resources navigator pointer asp tips navigator pointer structuring your scripts
The definitive ASP tips page
tips menu | printable single page version

Note: this is my old ASP tips page and is no longer supported. See the new Visualize web site..

ASP Coding and Style - Structuring your Scripts

All ASP scripts, other than very trivial ones, are worthwhile structuring into procedures, functions and SSIs (server-side includes). This will aid maintenance and readability considerably. A typical script could have the following structure:


<% Option Explicit   ' No implicit declarations thank you!
                     ' This should appear at the top of all
                     ' scripts to enforce variable declaration
%>
<!--#INCLUDE FILE='YourStandardIncludesHere.inc'--<
<!--#INCLUDE FILE='etc.inc'--<

<%

       ' Now declare any script level constants
Const sMYCONSTANTSTRING = "This remains constant"
Const sMYCONSTANTSTRING2 = "etc..."

       ' Now declare any script level variables
Dim iMyInteger, sMyString, bMyBoolean	   

       ' Now instantiate any script level objects
	   ' (ADO dbConns, dictionary object etc)
	   
       ' connect to database here
Set oDBConn = Server.CreateObject("ADODB.Connection")
oDBConn.Open "TestDSN"

     ' main processing here
	 ' .... etc 

 
      ' now close any database connections and free up objects 
oDBConn.Close
Set oDBConn = Nothing

'***************************

'  Private subroutines/functions here.
 ' Keep variables local where possible

'***************************

          ' have any standard footers if necessary here
<!--#INCLUDE FILE='YourStandardFooterIncludesHere.inc'--<

Obviously, the structure of the script will vary slightly depending on the nature of the script, but this is a good general rule of thumb. All includes (containing useful routines and commonly used code) are marked clearly at the top, it's clear which variables are at script level, and the main processing is near the top, hence easy to find.

Note the symmetry in the code, i.e. create, open, process, then close and free up memory. By keeping symmetry like this, you won't go far wrong on performance and efficiency of server resources.

Finally, I tend to keep my HTML output routines totally separate from the main logic, usually via a display routine at the bottom of the page or in a separate include, thus keeping presentation separate from the business logic.

 

DISCLAIMER: Note these pages are a free resource for anyone wishing to reference them. Although every care is taken to ensure their correctness, the author takes no responsibility for any errors or problems that may occur through their use, or indeed misuse. These pages are copyight of Dave Clarke, Visualize Software Ltd 1997-2000 (all rights reserved).


 


© Copyright Dave Clarke, 1996-2008