cleaner ASP pages using subs

S

Steven Scaife

I have decided to re-write the intranet site i created over a year ago. The
coding is pretty awful and hard to read cos I made the mistake of not
putting comments in or putting crappy comments in with the code. So I have
decided to try and make things neater by grouping it into subs. So i have a
sub to create the variables, a sub for the connection etc.

Only problem is when i call my subs, it says that the variable is undefined.
If i scrap the subs and put everything into the order they would be the page
works. I use the subs it doesn't.

Can anyone offer any insight or point me to a page that describes in detail
the solution i am trying to achieve

thanks in advance

sample code below.

my page would look something like
<body bgcolor="#FFFFFF" text="#000000" link="#804040" vlink="#008080"
alink="#004080">
<%
declareVar()
%>
<!--#include file="connection/connstring.inc"-->
<%
DBStrings()
%>

my subs are below as an example.
<%
sub declareVar()
'The declaration section
dim conn
dim strconn
dim physicaldbpath
dim strSQL
Dim RS
dim F
dim X

end sub
%>
<%
sub DBStrings()
set conn = server.createobject("adodb.connection")
conn.open strconn
strSQL = "Select Name, Number, Full_Number From AB_Dials;"
set RS = conn.execute(strSQL)

end sub
%>
<%
sub connClose()
RS.close
set RS = nothing
conn.close
set conn = nothing
end sub
%>
 
C

CJM

By declaring the variables within a sub, you are limiting the scope of the
variables to within that sun only...

Declare your subs in the main page, or if they are the same on every page,
put them in an external file and use #include.

To be honest, your attempt to clean up your pages may well further confuse
the problem.

If you have segments of code that are re-used on every page, eg. a header,
footer ot menu, you can obvious place these in a separate file and link them
in... but using subs doesnt sound like a very good solution...


Chris
 
S

Steven Scaife

Ok thanks, any ideas of how i can organise my pages so they are structured
nice or should i just stick with the standard way of doing it and comment it
properly. The intranet needs rewriting to use dsn less connections anyways
cos its using a dsn and the code i wrote is pap.
 
B

Bob Barrows [MVP]

CJM said:
By declaring the variables within a sub, you are limiting the scope
of the variables to within that sun only...

Right

Declare your subs in the main page, or if they are the same on every
page, put them in an external file and use #include.

That won't help with the "undefined variables" problem, unless you're
talking about creating an include page in which the global variables are
declared. Global variables must be declared outside of functions or subs.

However, I suggest minimizing the use of global variables. Global variables
can confuse things because their values can be changed anywhere in your
code, making debugging very difficult. Instead of global variables, use sub
and function arguments as much as possible to pass around your objects and
values.

OTOH, global constants can be a great thing. If you have a hard-coded
connection string, for instance, it would certainly be useful to encapsulate
that in a constant.
To be honest, your attempt to clean up your pages may well further
confuse the problem.

If you have segments of code that are re-used on every page, eg. a
header, footer ot menu, you can obvious place these in a separate
file and link them in... but using subs doesnt sound like a very good
solution...
Why not? I would say a combination of both techniques will certainly help
make things cleaner. Encapsulate the code in a function or sub which is
place in an include page. What is the downside of using functions or subs in
your view?

Bob Barrows
 
C

CJM

Bob Barrows said:
That won't help with the "undefined variables" problem, unless you're
talking about creating an include page in which the global variables are
declared. Global variables must be declared outside of functions or subs.

I *was* talking about global variables in an #include page... should have
made that clear, sorry.
However, I suggest minimizing the use of global variables. Global variables
can confuse things because their values can be changed anywhere in your
code, making debugging very difficult. Instead of global variables, use sub
and function arguments as much as possible to pass around your objects and
values.

OTOH, global constants can be a great thing. If you have a hard-coded
connection string, for instance, it would certainly be useful to encapsulate
that in a constant.

Personally, I hold the connection string in an application variable...
useful for maintaining separate development/production versions of the same
system. All pages in my systems can be copied between servers with the
exception of Global.asa, which is uniqure for every installation.
Why not? I would say a combination of both techniques will certainly help
make things cleaner. Encapsulate the code in a function or sub which is
place in an include page. What is the downside of using functions or subs in
your view?
Not necessarily a downside, but maybe lacking an upside.

Functions & Subs are very useful for re-using code withing a page. Also
useful for segregating a discrete & perhaps complex piece of code, for
example a complex algorithmn - or something that you want to take out of the
flow of the page/script.

I would only use them in these situations, though there is no reason why you
couldnt use them more - it's just that the benefits are questionable.

Also, you may find that if your code is sufficiently complex to merit plenty
of subs and functions (for the reasons outline above), that moving across to
a COM object might be an improvements.

I think you might be reading my response to the OP in a slightly
over-enthusiastic way! Until we can see what the OP was proposing, it's hard
to pass further comment.

Chris
 
J

Jeff Cochran

By declaring the variables within a sub, you are limiting the scope of the
variables to within that sun only...

Declare your subs in the main page, or if they are the same on every page,
put them in an external file and use #include.

This can often be more confusing. Variables declared in a sub don't
get changed by other code inadvertantly. And you don't end up
redeclaring variables accidentally because they don't show in the page
you're coding.
To be honest, your attempt to clean up your pages may well further confuse
the problem.

Subs and functions have their place, and should be used. While the
object isn't to clean up code, including commonly used functions in
every page can simplify quite a bit of coding. One example posted
recently is a Print function. Replaces Response.Write statements and
adds a VbCrLf for readability of the source page, and is a nifty
little function. Including that in every page is a no-brainer, and
not having the function in the page code by using an include file
cleans the page up.
If you have segments of code that are re-used on every page, eg. a header,
footer ot menu, you can obvious place these in a separate file and link them
in... but using subs doesnt sound like a very good solution...

Includes will clean up pages for commonly used code, but functions and
subs clean up repetitive code in a single page. The best of both
worlds is an include of common functions.

Jeff
 
D

Dan

I don't know how you code things but I like to put the *flow* code in a
separate ASP page (I'm not sure how common this is or whether it is
considered "desirable").

If you have a form on page that requires validation or depending on what his
entered redirects to another page, put the code that decides what to do next
on a seperate page.

For a simple example suppose you have a page called "contact.asp" which
contains a form allowing a user to submit their contact information. I
would have the form in "contact.asp" post to "post_contact.asp". And in
"post_contact.asp" I would put the validation code as well as the code that
determines where to go next (maybe..."thank_you.asp" or "error.asp").

Suppose you are creating a "wizardish" application, where the user has to go
through a series of steps and can jump back and forth between steps. IMHO
putting the logic to determine what to do next on the same page that
displays the form is messy and less readable.

I might be in the minority on this though.

Dan
 
B

Bullschmidt

<<
Ok thanks, any ideas of how i can organise my pages so they are
structured nice or should i just stick with the standard way of doing it
and comment it properly.
Here's an example of something that may give you some ideas for
structure.

' See what btn used, where opened from, or where referred from.
If Request.Form("btnClose") <> "" Then ' Close btn.
' Close.
Call ClosePg()
Elseif Request.Form("btnSave") <> "" Then ' Save btn.
' Set var.
Call SetVar("frompost")

' Save rec.
Call SaveRec()

' Show pg.
Call ShowPg()
Elseif Request.Form("btnNew") <> "" Then ' New btn from this pg.
' Set var.
Call SetVar("new")

' Show pg.
Call ShowPg()
Elseif Request.Form("btnDel") <> "" Then ' Del btn.
' Set var.
Call SetVar("frompost")

' Del rec.
Call DelRec()

' Set var.
Call SetVar("new")

' Show pg.
Call ShowPg()
Elseif Request.Form("btnShowList") <> "" Then ' ShowList btn.
' Set var.
Call SetVar("frompost")

' Show pg.
Call ShowPg()
Elseif Request.QueryString("CustID") <> "" Then ' CustID from Many pg.
Session(mstrSessionPrefix & "Cust-FromPg") = "custmany.asp"

' Set var.
Call SetVar("fromdb")

' Show pg.
Call ShowPg()
Elseif Request.QueryString("CustID") = "" Then ' Add btn from MainMenu
pg.
Session(mstrSessionPrefix & "Cust-FromPg") = "mainmenu.asp"

' Set var.
Call SetVar("new")

' Show pg.
Call ShowPg()
Else ' Nothing.
' This should never be the case.
End If

Best regards,
J. Paul Schmidt, Freelance ASP Web Designer
http://www.Bullschmidt.com
ASP Designer Tips, ASP Web Database Demo, Free ASP Bar Chart Tool...


*** Sent via Devdex http://www.devdex.com ***
Don't just participate in USENET...get rewarded for it!
 
S

Steven Scaife

Basically I just wanted to clean everything up. I wrote the site over two
years ago when I first learnt ASP, my second ASP site was a lot better, it
used disconnected recordsets and had comments and read better.

I used a combination of handwritten code and dreamweaver ultradev when i
became lazy, which was a big mistake cos its horrible and luckily so far on
my rewrite I haven't reached the pages with loads of code, some have like
500+ lines of code.

I originally used the request object but never specified what i was using so
just used request("textbox")
rather than request.form("textbox"). I'm probably leaving this org soon now
that I have graduated and hope to move into a web programmer position, so
this is for both the org and my benefit. i.e. I get back up to speed on ASP
they have a better functioning intranet that is easier to update.

I noticed an article on webmonkey that used classes but i haven't any
experience of these, this probably would have been a nice way of
encapsulating everything and using a sort of OO approach, but my degree
never taught object orientation so i didn't bother.

Basically, I wanted something that read nice, i have placed my commonly used
variables into a include file so now i have connect.inc and close.inc.
These open and close my database connections and dim the RS and strSQL
variables.

I have also tried to keep the ASP code seperate from the HTML as this makes
it easier to understand, i was wondering if it was better to use a sub that
looped through the recordset and wrote the contents into a list box etc. so
all i did within the select tags was this
<select "name>
loopintooption()
</select>

basically just things like that

Does this give a better understanding of what i originally asked.

ps. I like how I have started a debate on how people go about programming
there sites i feel important now, lol, hopefully more people will notice
this thread and get some tips from the pros.

thanks for everyones time
 
S

Steven Scaife

Thats what I did on my second ASP site i wrote, i don't like having 100's of
lines of code on one page having it submitting to itself, its not a problem
when its a tiny form but when there are lots on the form i too think it gets
messy

so i create a form page then submit to another page, the mastering ASP book
i have i'm sure says to submit back to itself seen it on tutorials on web
sites as well. Is it better to have the page submitting to itself or is it
again just personal preference
 
C

CJM

To be honest, Stephen, it doesnt sound like you are going to do anything
nasty, so just try out a new approach and see how it works for you.

There is a LOT to be said for readability, and many developers sacrifice a
*fraction* in performance for readable, maintainable code. I'm part of this
camp sometimes; none of my applications are hammered that heavily that I
need to mangle the code to gain a few clock cycles.

OO: My personal stance is that if the code is sufficiently complex to merit
using classes, it's probably worth using a COM object (which really is OO).
Should you decide otherwise, you will be at no real advantage or
disadvantage whatever you choose.

One small recommendation I would make is to rename your include files as
connect.asp & close.asp. Inc files are not interpreted by IIS, thus they can
be downloaded - revealing information about your application, eg. perhaps a
DB username & password. They work just as well as ASP files, but the user
cant get hold of them...

Other good advice:
http://msdn.microsoft.com/library/default.asp?URL=/library/en-us/dnasp/html/ASPtips.asp

And when you have time, browse through Aaron's site: http://www.aspfaq.com/

Chris
 
C

CJM

Personal preference IMHO.

I always use to post to a 2nd page, but like you have seen, plenty of people
recommend posting back to the same page. So I changed my approach, but I
soon found reasons why I prefered the two page approach, so I'm back to
square one...

CJM
 
J

Jeff Cochran

Thats what I did on my second ASP site i wrote, i don't like having 100's of
lines of code on one page having it submitting to itself, its not a problem
when its a tiny form but when there are lots on the form i too think it gets
messy

so i create a form page then submit to another page, the mastering ASP book
i have i'm sure says to submit back to itself seen it on tutorials on web
sites as well. Is it better to have the page submitting to itself or is it
again just personal preference

Six of one...

If you have a single form with a postback, all your code is in one
page and only one page has to be changed/moved/updated/backed up/etc.
Some developers will break everything into subfolders for similar
reasons.

On the other hand, using two pages, such as in an email response form,
may have advantages. I can have five different email forms, all
feeding a single page that sends the mail and generates a Thank You
screen. Then when I change mail servers, I don't need to remember
what pages to change the setting on.

Of course, you could store all these in a database and pull from there
for settings too. So there's more than one way to skin a lizard.

Jeff
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,073
Latest member
DarinCeden

Latest Threads

Top