PDA

View Full Version : good ASP coding practices


[o_O]
12-19-2002, 02:11 AM
In regards to a commercial application, I have some questions and grey areas to do with 'am i coding this the right way?' I mean sure it works but is this the proper way to do it in terms of speed, performance_and efficiency. Maybe just because i'm still such an asp newbie :o

I'm referring to ASP 3 (classic)

First thing is whether or not to declare the scripting language ("<%@ Language="VBScript" %>") at the top of each asp page? If i am using VBSCRIPT then what is the advantage / point of doing this?


!To Dim or not to Dim, This is probably one of the biggest grey areas, everything i have done so far with asp (not tha much) I haven't really declared the variables like this before making use of them, i usually just put:

variable = 123

as opposed to;

Dim variables
variable = 123


In my mind this does the same thing and uses less code? the other things is that apprently if you use Dim you have to use the 'Option Explicit' too that is extra code and i still don't know why or when you would want to do this?
What makes it more confusing is that some tutorial and references use Dim in their examples and some don't.

oracleguy
12-19-2002, 02:23 AM
What option explicit does it makes it so you have to dimension all your variables.

In general practice, it is best to dimension your variables. I know ASP3 doesn't have this but I thought .net did, and I know VB does. Is that you can dimension your variables as diffrent types, such as boolean, string, double, integer, etc. Doing this prevents data errors, like you accidently try to set 'abc' to a variable dimensioned as an integer.

allida77
12-19-2002, 02:23 AM
we always put

<%@ Language=VBScript%>
<%Option Explicit%>

on the top af all our asp pages. Option Explicit will force you to dim all your variables. So to answer that question yes you should always DIm your variables. To me you should always dim your variable because it makes code easier to debug and work with. If you dim variables you know through out the page what your variables are and what are not. There may be a better explanation but that is my 2 cents. AS far as speed goes learn functions, GetRows() and GetString() when working with ADO & Recordsets, and avoid session variables.

Oracle beat me....but with asp you can not do
Dim strFoo as String

oracleguy
12-19-2002, 02:29 AM
Originally posted by allida77

Oracle beat me....but with asp you can not do
Dim strFoo as String

I believe I mentioned that.

allida77
12-19-2002, 02:37 AM
duh I guess I need to read better.Sorry

glenngv
12-19-2002, 02:47 AM
Here is asp101's ASP Quick Tips you will surely find useful.

http://www.asp101.com/tips/

[o_O]
12-20-2002, 12:02 AM
hmm thanks that link is pretty good.

How about database connection scripts, include file that sits above the www_root right?

<!-- #INCLUDE File="../DBconn.asp" -->

:)

Also say that in my page i have quite a few queries to run throughout, at the top for the first query i would inc the dbconnection file and open the connection after finishing this query I close the recordset and set to nothing but leave the connection open becuase i know that 20 lines down i'll be popping back into asp and doing another query and it seems silly to close and open ? So i just leave it open and then on the very last query close it up and set = Nothing. good practice?

whammy
12-20-2002, 01:09 AM
I don't know if it's good practice or not... but that's what I do... and the applications seem to run fine. :eek:

I usually put everything in subroutines, and execute them depending upon conditions... this is probably a holdover from what I used to use in BASIC when I was a kid, before I abandoned computers for a decade and a half (and most of my program flow is executed just like the following example), i.e.:

Call OpenConnection() ' This sub contains my ADODB.Connection code
y = 2
If 1 = y/2 Then
Call SomeSub()
Call SomeOtherSub()
Else
Call SomeSubThatSaysYouNeedToDoSomethingElse()
End If
Call CloseConnection()


I have no idea whether this is the "best practice" in regards to where you open and close your connections, I'd assume you want to close any references to your connection object as soon as you have no further need for it.

A couple of advantages of doing it like I showed above though, is number one, modularization - if you need to switch around subroutines because of a new specification for your program, it's no big deal... you can always open and close your connection again by calling the appropriate subs, and I've never personally had any problems with leaving the connection open. Number two, who needs documentation when your program flow is that straightforward, and you name your subroutines clearly? ;)

I dunno if this helps or confuses the issue... anyone have any further input (or a message saying "don't do that, whammy!")?

As for defining the language at the top of the page, I always do that - and I ALWAYS use Option Explicit, because it helps in debugging!

:D

[o_O]
12-20-2002, 04:28 AM
So you have heaps of asp bits here and there in the page. Would you Dim all varibles at the top of the page or spread out just before they are used? in other words



Dim this, that, baseball, pooh, orange, paper, pen1, scramble, recordset3

....

..asp using pooh here..

..html..

..

asp using orange here

..etc

or



....

dim pooh
..asp using pooh here..

..html..

..
dim orange
asp using orange here

..etc


:cool:
I'm guessing the second is the norm, although the first does have an advantage of being able to see and edit all variable names in one place?

BigDaddy
12-20-2002, 04:40 AM
The first is best. That way, if you have a question about the variable, you can always find it at the top.

allida77
12-20-2002, 04:41 AM
If the variable is being used throughout the scope of a page I usually declare it at the top. Otherwise you will always looking through your page to figure out where you dimmed your variables. If you are only using your variables within a sub or function scope then I declare the variables inside the sub or function.

[o_O]
12-20-2002, 04:53 AM
Dim a variable but then you want to give it a different value

use Set varaible = 'new value'?
Just use 'variable = new value'?

glenngv
12-20-2002, 06:16 AM
You use the keyword Set only when creating an instance of a specific object or when creating an instance of a Class or RegExp.


<%
'instance of an object
Dim Anyvariable
Set Anyvariable = Server.CreateObject("Scripting.FileSystemObject")

'instance of a RegExp
Dim SearchPattern
Set SearchPattern = New RegExp
%>

[o_O]
12-20-2002, 06:59 AM
I see.

I have a database connection script which i include on almost every page. It's shown below I decided to just Dim the variables in this block of code, (? :) )

<%
Dim connString, connection
connString = "Driver={MySQL};" _
& "SERVER=localhost;" _
& "DATABASE=mine;" _
& "UID=mine;" _
& "PASSWORD=mine"

Set connection = Server.CreateObject("ADODB.Connection")
%>

I of course include that on all the pages with
<!-- #INCLUDE File="connect.asp" -->

but on a couple of the pages that this file is #included on I now get the following error

Microsoft VBScript compilation error '800a0411'

Name redefined

connect.asp, line 2

Dim connString
----^




I'm not sure why though because I do not assign any new value to this variable, I just use it a couple of times on the page like so:

connection.Open connString
recordset.Open SQL,connection
etc

whammy
12-21-2002, 02:10 AM
Are you including a file which ALSO includes the connection file?

[o_O]
12-21-2002, 04:19 AM
Nope but what i've decided to do is this.

Take out the Dim from the connect.asp and at the top of every page put:

<% Option Explicit
Dim SQL, connString, connection
%>


Since those 3 variables are used throughout and on all pages, I can see any obvious problems with doing that (yet )

And then I will Dim all other variables in their respective code blocks before use.

[o_O]
12-23-2002, 02:15 AM
The correct way to code an SQL query is with a ';' at the end right? It works both ways so :confused:

oracleguy
12-23-2002, 03:41 AM
The name redefined error means that you tried to dimension a variable with the same name later or before in the page.

Even if you have a dimension inside an if statement that isn't executed because the conditions aren't met, the variable is still dimensioned; or at least you can dimension somewhere else on the page too.

[o_O]
12-29-2002, 06:08 AM
Which do you prefer and is there any performance increase in using the first way?


Recordset.Fields("field_name")

or

Recordset("field_name")

[o_O]
01-01-2003, 01:51 AM
Is it o.k to have long SQL queries stretch across the page? apart from readability, can it actuallyt cause any problems?

for example:

SQL="SELECT p.ProductName, c.CategoryName, s.SubCatName, pd.BriefInfo, m.ManufactureName FROM Manufacture m, Products p, Product_Detail pd, SubCategory s, Categories c WHERE p.ManufactureID = m.ManufactureID AND s.SubCatID = p.SubCatID AND s.CategoryID = c.CategoryID AND pd.ProductID = p.ProductID AND p.ProductID = '125'"

(^ getting data from 5 tables)

Do you generally just leave it as one big line or break it up?

whammy
01-01-2003, 04:29 AM
I guess that's your preference. I usually just make one long line myself unless it's a really really big query...

[o_O]
01-01-2003, 07:12 AM
:cool: Just wanted to make sure there were no potential 'problems' with doing that.

BigDaddy
01-01-2003, 04:33 PM
It's interesting looking at different folks' code. In my new job, one page has an update query with about 6 different conditions to update:


The query was in the format of:

sql = sql and *******
sql = sql and *******
sql = sql and *******



It was actually very simple to find the breakpoint between conditions to delete one or comment out one if I wanted to. I could just remove one line to remove a condition.

whammy
01-01-2003, 05:14 PM
I'm using a few queries like that in an application you are probably familiar with, BigDaddy. ;)

I had to do something like that yesterday to modify one of Little D's admin apps, as well - no other way. I love "Select Case" in these instances. :)

BigDaddy
01-01-2003, 06:59 PM
Yeah, I've seen him build queries like that. He was the only one around there I remember specifically doing that. Step2 was a bit like that.

whammy
01-01-2003, 07:02 PM
Something like this?:

If Request.Form("SearchText") <> "" Then
MyQuery = "SELECT * FROM TABLENAME WHERE " & Request.Form("FieldName")

Select Case Request.Form("SearchType")
Case "Equals"
MyQuery = MyQuery & " = '" & SQLFormat(Request.Form("SearchText")) & "'"
Case "Contains"
MyQuery = MyQuery & " LIKE '%" & SQLFormat(Request.Form("SearchText")) & "%'"
End Select

'Response.Write(MyQuery) : Response.End ' for testing
Set rs = Conn.Execute(MyQuery)
Do While NOT rs.EOF
' results here
rs.MoveNext
Loop
Else
'Response.Write("You didn't enter anything to search for!")
End If

oracleguy
01-01-2003, 07:34 PM
Originally posted by [o_O]
Which do you prefer and is there any performance increase in using the first way?


Recordset.Fields("field_name")

or

Recordset("field_name") <-- This one is more efficent performance wise. Less '.''s in your program, and the faster it will run. Of course it's not an major, major performance difference but thats supposedly how it works. At least thats how it is with Visual Basic so I assume it could be true for ASP.

[o_O]
01-01-2003, 07:53 PM
Old post i found through google:


If you don't use ".Fields", ASP checks every collection in Recordset until it finds "field_name". That is slower than specifying the collection explicitly. The same applies to other objects like the Request object (e.g. Request("form variable") vs. Request.QueryString("form variable")).

BigDaddy
01-01-2003, 10:48 PM
I wondered about using request.form("variable") or request.querystring("variable") vs just

request("variable")

This same stuff I'm working on in my new job doesn't specify querystring or form. It just gets it from the request object.

[o_O]
01-01-2003, 11:20 PM
On my results page some variables could be coming via a QueryString or Form so in cases like that I have to use 'Request("variable")' but otherwise I think specifying 'Request.whatever("variable")' is better since as stated above, it doesn't have to loop through all.

It would make sense to think that the same applies to the 'Recordset.'


ASP.NET / VB.NET don't accept the shortened default forms ?

oracleguy
01-01-2003, 11:59 PM
Hmm... I stand corrected.

[o_O]
01-02-2003, 01:38 AM
It's not like it really makes a noticatble difference either way for performance for your everyday app though? but it could be considered 1 of those 'good ASP coding practices' :o and probably important for a big site which is going to be under heavy load and where the slightest performace gains are paramount I guess. Not like I really have any experience with that though so.. :)

this thread is good.