Microsoft KB Archive/299985

= How To Write Readable and Maintainable ASP Scripts =

Article ID: 299985

Article Last Modified on 7/15/2004

-

APPLIES TO


 * Microsoft Active Server Pages 4.0

-



This article was previously published under Q299985





IN THIS TASK
SUMMARY
 * Write Code That Is Readable and Consistent
 * Plan Your Routines Carefully
 * Package Reusable Code
 * Troubleshooting

REFERENCES



SUMMARY
This article provides some guidelines on how to write Active Server Pages (ASP) script that is easier to read and maintain. As your Web application grows more complex, it is not uncommon for ASP scripts to grow to hundreds of lines. If later you experience application errors or need to rework part of your code, it can be difficult to isolate problems if your code is complex and hard to read. This article offers best practice coding guidelines that may help avoid this scenario.

back to the top

Write Code That Is Readable and Consistent
 Use consistent naming conventions.

How you name the constants, variables, and objects that are referenced in your code will determine how readable your code is. If you always use a similar prefix such as &quot;str&quot; for variables that contain string data, your code is easier to understand. One particularly helpful approach is to avoid using short, cryptic variable names; this is almost never worthwhile. It is far better to use longer names for the sake of clarity. You can easily follow a consistent naming scheme such as using &quot;camel&quot; notation (MyLongVariableName) or underscores (My_Long_Variable_Name) to make for clearer code. For detailed help on naming conventions, see the &quot;References&quot; section.  Format your code consistently.

When dealing with markup languages such as HTML or XML, many developers prefer that all of their the tags appear in uppercase or lowercase (for example, either  or but not ), which makes them easier to distinguish from other code. You can also indent portions of the code that are logically subordinate to reveal the logical structure. For example, the following JScript function begins at the left margin, the &quot;If-Then&quot; clause is indented several spaces, and the code within is indented still further: function MyFunction {  if(SomeVar == true) {      Do_Something; }  else {      Do_Something_Else; } }   Comment your code extensively.

Nothing can substitute for a simple, contextual explanation for what the variable or routine is supposed to be. It helps to have both a high-level description, such as &quot;This routine updates employees biographical info in the Employees database.&quot; It is also good to have a more technical description that includes what is necessary for this code to run, inputs, outputs, required variables, and so on. Many developers also find it useful to comment who wrote the routine and when it was last updated, although many source code control programs (such as Microsoft Visual SourceSafe) handle this aspect automatically. Usually the best way to comment a routine is to place more detailed or narrative type comments above the routine and sprinkle single-line descriptive comments throughout the routine. Below is a sample of commented code: 'Written by: John Smith 'Last Updated: 2/05/2001 'Description: 'This function updates the employees table...

Function UpdateEmployee (intEmployeeID, strLastName, strFirstName)

If SomeVar = true Then 'Add inline comments within your functions. Do Something End if End Function NOTE: Remember that VBScript uses an apostrophe (') to denote comments, whereas JScript can use two forward slashes (//) to indicate comments on one line or can denote multiple line comments beginning with a forward slash/asterisk (/*) combination and ending with an asterisk/forward slash (*/) combination.  Locate variables and constants in a common place.

Rather than declaring variables and constants throughout your routines when you need them, it is easier to declare them all at the top of the routine. If you are dealing with &quot;page-level&quot; variables in ASP, declare them at the top of the page in a cluster. Then, if you need to troubleshoot them later, they are easy to find.

back to the top

Plan Your Routines Carefully
 Avoid repetition in your routines.

If you find yourself writing multiple routines that look almost identical, and the routines perform a very common function (such as updating tables in a database or writing an HTML table that is filled with database data), you may be able to create one common routine that replaces four similar ones. In addition, if you have multiple &quot;If&quot; clauses in a routine to test one variable, you may be able to convert it to a simpler logical structure, such as a case statement. For more tips about this and for extensive coding samples, see chapters 13-17 of Steve McConnell's Code Complete, which is listed in the &quot;References&quot; section.</li>  Avoid excessive nesting in routines.

&quot;Nesting&quot; refers to logically subordinated structures, such as the &quot;If&quot; sample to follow, case statements, &quot;For Next&quot; statements, and so on. Every programmer has struggled in trying to decipher routines that are nested many levels deep, such as the following routine: Function MyFunction If SomeVar = true Then If SomeOtherVar = true Then For Each item in MyCollection If YetAnotherVar = true Then Select Case FavoriteColor ...                       ...                    End Select else Select Case FavoriteFood ...                       ...                    End Select End If           Next End If   End If End Function Even if routines such as the preceding routine are carefully indented and commented, they are extremely difficult to decipher and troubleshoot because you must sort out multiple layers of logic. The preceding routine is nested five layers deep. Although there is no hard-and-fast rule, in general, if your routine is nested more than two or three layers deep with logical code structures such as those above, it is probably becoming too complex. A better way to handle logical complexity is to simply break the code into multiple smaller routines, each of which accepts parameters, does some processing, and then passes off the work to the next routine. If a routine such as the preceding routine is broken into two or three smaller routines, each routine is only a few lines long and nested only one or two layers deep; thus, it is much easier to follow the flow of the code. </li> Avoid long routines.

This relates to the previous item. The longer that a routine gets, the harder it is to keep track of what the routine is doing. You may be tempted to try to pack more and more into one routine. In general, a routine should do one thing and do it well. If a routine has to do several complex steps (such as validate the data that the user submits, call a stored procedure, process the results, and display an updated page to the user), you may be better to write one &quot;umbrella&quot; routine that simply calls several other routines, each of which performs one of these steps. You can find more tips on how to construct routines in chapters 4-7 of Code Complete.</li></ul>

back to the top

Package Reusable Code
 Package common code in COM DLLs.

When you identify and build common, reusable routines, particularly code that handles database operations, you can drastically simplify your ASP scripts by compiling the common routine into a Component Object Model (COM) dynamic-link library (DLL) using Microsoft Visual Basic or Microsoft Visual C++. Then, you can create objects from the compiled component and call methods from your ASP page to accomplish with two or three lines of ASP script what may otherwise take 20 to 100 lines or more. Furthermore, when you compile code into a DLL, you gain the best possible performance for your code because compiled code outperforms interpreted ASP scripts. You also gain the advantages of working in the Integrated Development Environment (IDE) of one of the Microsoft Visual Studio languages, which gives you better debugging facilities than you have in ASP. For an example of how to package a commonly used ASP script in a compiled DLL, see the Microsoft Knowledge Base article Q299988 in the &quot;References&quot; section, which demonstrates how to create a compiled DLL that automatically writes data from a database into an HTML table.</li> Package common code into Windows Script Components.

Windows Script Components (WSCs) are a newer Microsoft Scripting technology that, similar to a compiled COM DLL, enable you to package your reusable scripts. In this case, however, the component is not compiled, though it is a COM component that can be registered and called from an ASP page. WSCs are simply XML files that contain the necessary information so that the operating system treats them as normal COM components. Note that because they are not compiled, you do not gain the performance advantages or the advanced debugging features that you do with a COM DLL. In addition, these components are a newer technology and are not as well tried and documented yet. However, there is a good scenario for using WSCs: WSCs enable you to package your code and simplify your ASP scripts during development, and they provide flexibility as you continually modify your code because you do not have to continually recompile them. When you move your application into production, you can move the WSC code into compiled components to gain the performance advantages.</li> Use Server.Execute and Server.Transfer.

Another way to package scripts, which is less known and thus underused, is to use the new Server.Transfer and Server.Execute methods with Active Server Pages 3.0, which ships with Windows 2000. Unlike using server-side includes for packaged scripts (see the next item), these methods allow you to package ASP scripts in separate files as if they were separate &quot;modules&quot; or components and then transfer control to those pages to run the code on them without losing context of the page from which you started. For a description and sample of these ASP methods, see the &quot;Transferring Between .ASP Files&quot; topic in the &quot;Sending Content to the Browser&quot; page, which is listed in the &quot;References&quot; section.</li>  Use server-side include files.

This &quot;tried and true&quot; method is still probably the most commonly used method to package common ASP scripts for use in Web applications. A typical approach is to put your common code (such as a page header, a group of constants or variables, or a common routine) into a separate file and then insert an &quot;include&quot; at the point where you need this code to run in your ASP script. For example: For an overview of how to work with server-side includes in ASP applications and sample code that demonstrates this method, see the Microsoft Knowledge Base article Q299982 in the &quot;References&quot; section.

Server-side includes are a useful technique because after you place common code in an include file, you can reference it from multiple pages in your application. If you need to change that code, you only have to change the code in the include file, and the code is automatically updated everywhere. However, one disadvantage of includes is that your code is less secure than some other options, and includes provide no real packaging of your scripts. Includes simply include all the content of the include file, whether or not it is used in a given instance of your code. </li></ul>

back to the top

Troubleshooting
There are no real pitfalls of taking the time to plan and write code that is easier to read and maintain. It may take more time initially, but it will save a lot of time in future application maintenance, especially when you need to troubleshoot problems or when the programmer who wrote the code moves on and a new programmer is left to figure out the code.

back to the top

<div class="references_section">