Peer into the brains of a professional programmer to learn how to become a better coder and more easily maintain your code for management and easily allow others to understand.
Terms of Agreement:
By using this article, you agree to the following terms...
You may use
this article in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.
You MAY NOT redistribute this article (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.
You may link to this article from another website, but ONLY if it is not wrapped in a frame.
You will abide by any additional copyright restrictions which the author may have placed in the article or article's description.
First off - these are not set in stone. Every programmer has different ideas of how things sould be - and companys too. These are mearly a guide. Even I do not follow these to perfection. But they are the general ideas behind the code that I post to this site. Also, I am always updating my thoughts on how to program. I'll attempt to update this article as time progresses.
Directory Structure
The beginning of these standards doesn't deal with the code, but the directory
structure.
I am uncertain how many people here in my industry host multiple domains
(or even subdomains) on a machine. For the purpose of easier management,
Here is the structure that I use.
So, if I have a domain called "www.lewismoten.com", the site would be located
within the following directory:
C:\InetPub\wwwRoot\LewisMoten.com\www\
Domains without a sub domain (ie - lewismoten.com without the "www.") usually
point to the same content as the sub domains "www", so just simply point
"lewismoten.com" to the "Lewismoten.com\www\" directory when you setup IIS.
Ok, This little tid-bit isn't a standard, but a brief tutorial. I have only 1
IP address, yet I have multiple domains (and sub-domains) on my computer. Here
is how I do it with Windows 2000 Advanced Server.
In internet service manager, create a new web site. The wizard pops up and asks
for some info. As a standard, I type in the full domain name including sub domains.
Actually, I create two. One for www.lewismoten.com and one for lewismoten.com.
The main part
you want to pay attention to is the Host Header for the site. You can't assign
multiple host headers to a single web site (at least I havn't attempted to do it yet),
so that is why we need two web sites. In here, I would type www.lewismoten.com.
The next part asks you for a directory location.
They both point to the same directory (\Lewismoten.com\www\).
This should be enough to get you on your feet to multiple domain hosting.
Unfortunatly, windows 2000 professional doesn't support more then one website,
so your gonna have to dig deep in your pocket just to get the advanced server for
multiple domain hosting in this regard on a single IP address.
Application Structure
When creating an application, make a name that relates to the application.
For example, a website that deals with stocks may exist in a folder called
"/Stocks/" rather then "/s239123/". It is easier to identify and manage
applications in this way.
Look at the following list of the suggested directory structure for your
application:
ClientScripts - These are your javascript and vbScript files that you
may need to send to the client. It is always best to seperate your script
from the web pages so that the scripts are cached on the users browser and
quickly load for new pages that make use of the same script.
ActiveX - If your site uses DLL's, you may want to place them in the appropriate
directory along with a batch file that will register the DLL's from the command prompt.
This is primarily for easier management if you need to copy the application to another
computer. The controls directory should contain active x controls that you make available
on the web pages.
Data - This is the location for all your client side data - except for the
SQL folder. The sql folder should contain batch files for transact SQL to setup
your database with the appropriate schema and any data needed for a fresh install.
If you are using an access database - it is best to have them located in a directory
that web users can not access. If this is not an option, then make a sub-directory
from the data directory named "Access" and place the files in here. You should have
2 of each database. One is the "Live" database and the other is the database for a
fresh installation.
Includes - Include files are server-side script files that are included in other
asp pages. Others may suggest giving them an extension of ".inc" or ".txt". I always use
".asp" because Visual Interdev does not recognize the other two when it comes to object
inheritance and coloring the code for easier reading. I also incude a sub-directory called
classes. The more recent versions of vbScript allow you to create classes and I seperate these
from the other code and think of them as little black boxes.
Media - If your site only includes images, then you may want to go with the generalized
standard of just naming this directory "Images". I sometimes think ahead and consider the other
types of media a site may have. Flash is the primary reason. Sometimes I give it its own directory
besides images - but placing the two in a media folder makes more sense.
StyleSheets - If your like me, your site has style. I like to create different styles and
give them there own sub-folders off of the style folder. This way, i can tell the difference between
the Misc. style sheets accross the site and the Main Style Sheet for the sites theme. You may want
to consider placing "some" images in this folder if they relate directly to the stylesheet.
Content - This is completly optional. Sometimes I use it, sometimes I do not. The main reson
you may use this is in the case that you have a little too many folders off of your application root.
More often then not, I do not use this folder - but it is here mearly as an option that you may want
to consider.
File Structure
File names are important to the programmer, and can sometimes help when a visitor
calls in with a problem and needs to identify a web page. I've dealt with one project
where a programmer decided it was best to use a giant "Select Case" statement on
a query string named "Action" to determine wich include file to load. I had a tough
time explaining to him that even though the other includes were not used, they were still
compiled with the page at execution. Also, a client calling in would have to read
the query string as well as the web page. Not too much of a hassle you may think - unless
the query string is very long. Which it was.
I like to break everything appart into seperate pages. Some people even post data back
to the same page. I like to sperate that as well. Let me give you an example of the
file structure I may have in an administration directory called "Users".
/Users/addUser.asp ' Displays form to add a user
/Users/addUser.Now.asp ' Commits action to add a user
/Users/delUsers.asp ' Confirms action to delete users with details
/Users/delUsers.Now.asp ' Commits action to delete selected users
/Users/edtUser.asp ' Displays form to edit specific user
/Users/edtUser.Now.asp ' Commits action to edit the user
/Users/lstUsers.asp ' Lists all users in directory
Templates with JavaScript
I've recently begun to re-think about how I make my websites. It used to be that I included a file
of ... pretty much static HTML at the top and the bottom of the page. Todays web-browsers are comming
with javascript as a standard. What I have begun to do is convert all that HTML to javascript and place
it into a client-side script file. At first, I started running into problems. Things like - what if
something is supposed to show up in the template on one page, but not others? What if I want to display
the number of people logged into the site? And a few more. I quickly found the answer though.
In the web page, before I call the javascript file, I define a few variables. Look at the following.
<SCRIPT language="JavaScript" src="ClientScripts/Template.js">
<SCRIPT language="JavaScript">
var pStrUserName = '<%=Session("UserName")%>'
var pBlnLoggedIn = <%=LCase(CStr(IsEmpty(Session("UserID"))))%>
var pLngVisitors = <%=Application("Visitors")%>
if(window.templateLoaded == true){document.write(templateHeader())}
Notice how I used a variable assigned to the window object to see if the javascript loaded? This helps keep errors
down so the user isn't discouraged. Now comes the next problem - what if the user does not have javascript, or better
yet - what about search engines? My friends, I present to you a real use for the
OK, we got past a hump and hopefully reduced the bandwidth of our pages by about
... 5 to 10 kb? It all depends how big your template file is to begin with.
This should also increase performance just a wee little bit since there is less
for your ASP pages to process. Remember - ASP = Glue.
Now you may be thinking that your sites template is pretty complex. I've dealt
with a lot of complex variations of templates and basically come to this thought. If you can write it in vbScript on
the serverside, then you can do it with javascript on the client side. It just depends how much time you are willing
to dedicate to solving the problem and increasing performance. I wouldn't however - suggest editing your template on
a live site. Make a local copy first. Your visitors will be happyer.
One last little problem I see with this is for a vast majority of unpopular search engines. They usually look at the
first few lines of text on the site for a description. You can always place a few lines at the beginning of the noscript
tag. If you do, then I would suggest adding an Horizonatl Rule tag to seperate it from your links.
Editing Files
Never edit a file on a live site. I've had a few people do this on me and suddenly I have visitors sending me emails
and clients calling me asking why there site is broken. Copy the file to your own hard drive and edit it. Then - after
testing the file, copy the file to the website.
vbScript Format
This is a big one. Many programmers have many different ideas of how you can do this. These are my own personal
commitments and are by no means set in stone. I am always changing my standards when I see a better way. It is
now that I am finally documenting them.
Tabs - Tabulate your code for easier reading.
If ThisVariable = ThatVariable Then
Do Something Cool
End If
Notice that the second line "Do Something Cool" has been tabbed? Any statment that requires a closing statment
such as "For", "While", "Do", "Select Case", "With", etc. Should have its contents indented.
Comments - comment your code so that others can understand what you are trying to do. It may seem that
the code is screaming out to you, clear as a bell, to you - but some programmers who are not so experienced, or
even clients for that matter, may need some help.
' Make sure the two values are equal
If ThisVariable = ThatVariable Then
Do Something Cool
End If
I also like to leave a space between the comment delimiter and the comments themselves.
Characters Per Line - I usually like to limit my pages to no more then 80 characters in width.
This helps to prevent scrolling horizonally when reading my code on the more common screen resolutions
today.
Use Line Continuations - If you have a line that is just to long, don't be afraid to break your
strings and/or code apart on multiple lines using the underscore character.
Procedure Seperators - At the beginning and end of each procedure, I use a comment followed by a
space and 78 dashes. This helps me find the beginning/end of each procedure.
Procedure Placement - I place procedures at the bottom of the code. This is so that the guts of
the code can be seen first. Sometimes I place the procedures in alphabetical order, but more commonly,
I place the procedures in the order in wich they are called from the main part of the code.
Main() - If I can, I try to place all code in procedures. The main guts are placed in a sub called
"Main()". This mimics other programming languages because they usually require this name to begin with.
Do code before sending output - This is a big one. I attempt to execute every piece of functionality
that the page offers before attempting to write out the results. WHen this is done, I'll see an error rite
away if any come up rather then hunting for it in the source code if a tag isn't closed when the error occurs.
(examples - SELECT, TABLE, TEXTAREA, etc.)
Variable Names - This is where programmers battle it out. Even though vbScript doesn't use
types other then variants, it is helpful to understand that there are sub-types as well. A string
of "1" is not equal to the number 1.
When it comes to defining variant names, most programmers use the Hungarian Notation - or a slight
modification closly related to it. Hungarian was primarily developed for C by one of the programmers
at Microsoft, but has been adapted for many other languages over time. Here are my methods.
Dim StrName - String (Unicode)
Dim BinName - String (Ascii)
Dim LngName - Long
Dim IntName - Integer
Dim BytName - Byte
Dim ClsName - Class
Dim ObjName - Object
Dim DtmName - Date/Time
Dim VarName - Variant
Dim BlnName - Boolean
There are also a few scope variables that I prefix the variables with.
Dim StrName - Page Scope
Dim gStrName - Global Scope (Usually found in Include files)
Dim pStrName - Parameter (Used for arguments passed to Subs and Functions)
Dim lStrName - Local Scope (Used within the subs and functions themselves)
There is one last part of my naming conventions and that is to define Arrays. I add a suffix to the
end of my variables "Ary" so that if i had a List of numbers, I would call the variable "LngNameAry".
Variable Declaration - Always declare your variables. This means that if you use a variable anywhere on your page, then you should have it defined somewhere on the page using the Dim or Const keywords. I always place the declarations at the top of the page along with comments describing "ALL" variables. If the variable has local scope (within a procedure) then declare the variable at the beginning of the procedure before you write the code.
To hlep you make certain that all variables are declared, you may insert "Option Explicit" on the first
line of your code. It will result in raising an error any time a variable is found that hasn't been
previously declared.
Also - use names that make sense. In javascript, I often see that "i" represents a counter position, or an index. This is pretty common and widely known. When others begin to use single letters for other variables, It becomes very confusing to understand what the code is doing at a quick glance. I often find myself renaming variables in other peoples code just so I can comprehend the process being carried out.
If there is a common known name for a variable (Such as Conn for ADODB.Connection), Then by all means - use that name!
When creating the names, I use lower case letters except for the first letter of each word. Look at these for an example.
Dim StrThisIsAVariable
Dim StrAnotherOne
Dim LngLookHere
That shoud give you a basic idea. Some people Don't capitalize the first letter of the Variant Type (Eg - the "S" in "StrAnotherOne". This is fine by my standards. I can easily see what it is. The capitalization is primarily to help reading the variables.
Constants are sometimes treated differently. It is suggested that you use ALL UPPER CASE LETTERS seperated_by_an_underscore "_" character. Look at the following examples:
Garbage Collection - Any objects that are created "MUST" be removed from memory to allow resources
to become available.
Set ObjName = Nothing
Tabbing in columns -
This one isn't used quite so often by others in the industry, but I find it pleasing
to the eye. If I have a few variables being assigned values, I try to tab the values
into a seperate column. Take this for example:
Notice how everything is lined up? I also do the same thing when I declare variables.
Dim LngMemberID ' Identification of member within database
Dim StrMemberName ' Member login name
Dim StrMemberPassword ' Password for member to login with
Theory Behind ASP
As most of you may have heard ... ASP is supposed to be the GLUE to a dynamic
website. Unfortunatly, it seems that everyone places all business logic within
the ASP. And why not? It is so convienient, easily updatable, and easy to
distribute. With .Net, The original theory behind ASP will no longer apply.
When I first got into the IT industry (professionally that is), the project I
was working on consisted of a Transaction Server (Today it is known as COM+)
that contained DLL's compiled by Visual Basic. All of the main logic was located
within them and the asp page called upon them for the data. It would then format
the page according to the data returned. It didn't do any more logic other then
that. This is the guts of the original theory behind ASP.
Today, XSL follows the GLUE theory, in that it doesn't do too much programming.
As always any post by Lewis is carefully read by me and I loved his work from the beginning! He helped me become a better coder and I adapted his coding techniques unlike others I say "Lewis-Style" DOES improve your coding. I teach all my collegues this way of coding just to make sure we can exchange code better.
As always my deepest gratitude to my good friend Lewis may our paths cross more often my friend!
Kudos to Lewis and his LCAD certificates. (Lewis Certified ASP Developer) Just kidding :P But this man would deserve his work beeing recognized in such a manner!
LEWIS YOU RULE!!
J.J., The Netherlands (If this comment was disrespectful, please report it.)
I wish everyone would use some sense, as this guy does :) (I use the same stuff whenever i code, just to make it more readable for both me, and others who might be viewing my source code).
Kudos to Lewis for taking the time to write this out! Ian! Make this a must-read file or something :)
Peter Schmitz. (If this comment was disrespectful, please report it.)
This is a well written article. Many newcomers to embedded scripting, more than any other area of programming, fail to appreciate the importance of logical structure.
However, I do disagree with the author on some points:
(If this comment was disrespectful, please report it.)
Client-side Scripting - to be avoided unless it is actually *necessary*. Rationale: the developer has no control over the execution environment of Javascript. Far too many times, I have been browsing have come to a page that is apparently static, to be greeted with yet another 'Object Expected' error. Even when running a vanilla copy of IE5. The situation is far worse for users of Mozilla or old browsers. The developer can control the server. Use that fact. If you are worried about resource usage, the alternative to using ASP or javascript for for anything unchanging is to make it static HTML. Many developers compile their site from some more easily editable form, e.g. XML, before putting it on a server. It is very easy to add navigation bars and the like at this stage. (If this comment was disrespectful, please report it.)
Variable Capitalisation - The author's style is quite common, although the capitalisation of type prefixes is a little unusual, however if your code ever has to be read by non-native speakers of English, you should use underscores rather than capitalisation: they find it much easier to read, e.g. my_variable_name. Although VBScript is not case sensitive, you should also avoid the habit of excessive use of capitalisation in case you ever end up coding in a case-sensitive language. It is incredibly irritating to continually have to check whether a variable is spelt UserName or Username, for example. (If this comment was disrespectful, please report it.)
Comments - The code explains what the code does, and if it isn't clear, you need to refactor to make it so. It is a waste of time and hence money to reiterate in English what is already written in code. Comments should be used to briefly summarize whole blocks of code, and to explain *why* the code does something, not how it does it. There are of course exceptions to this rule: if the code really is obfuscated and that's someone else's fault, it is of course better to comment than not to. (If this comment was disrespectful, please report it.)
Hungarian notation - This is a really pointless idea in statically typed languages, but I have to admit that it is more useful in a scripting language. Nevertheless, I think using type prefixes for such common and obvious types as numbers and strings is perhaps excessive. Other than those, I agree with every point made. (This 1000-word posting limit is a real pain) (If this comment was disrespectful, please report it.)
Thanks Jamie, I'll have taken some of your knowledge pretty well and may recompile this document after reading your comments. As far as templates go, I develop for Netscape 3.04g and then test on the most recent browsers. This seems to be the best approach so far. There are many tricks that I use to be compatable, but if people would use the basic "document.write" for static parts of ASP pages, you would reduce bandwidth. (If this comment was disrespectful, please report it.)
Variable Capitalisation - "capitalisation of type prefixes is a little unusual", hmmm... I can change. No biggie. I'm always looking for a way to improve and work with others. Comments - I get your point pretty well and find myself commenting on blocks pretty often rather then a line-by-line basis. Except when it comes to declaring variables - i comment them all. As far as underscores go, They are commonly reserved for Constants. (If this comment was disrespectful, please report it.)
As I said in the beginning, everyone has there own way of standards. Some even use them religiously. As far as your hungarian language ideas, I'll have to agree to an extent. Sure, You can look at the part where variables are declared in Typed languages, but when your deep down into the code, others might find it more convienient to see the prefix rather then hunting for the variable declaration. Thanks for the comments Jamie. They are much appreciated as they shed some light on how others apply standards in the profession. (If this comment was disrespectful, please report it.)
Lewis, Thanks. Perhaps Jamie should go write his own standards, instead of picking apart what you so kindly took the time to write. (If this comment was disrespectful, please report it.)
Awesome...if anyone hasn't checked out ALL of Lewis' code, they're missing out on REALLY valuable coding techniques. My skills have improved at least tenfold (and I was a pretty good programmer already) within the last month by just analyzing his approach. His code is the best I've seen! Awesome! BTW, I printed this out and have it hanging up! (If this comment was disrespectful, please report it.)
Mr. webb wrote --The code explains what the code does--.
This statement is ridiculous. Anyone who has had to take on maintenance or modification of an existing application will understand the value of liberal comments.
In non-trivial applications, there are multiple levels of abstraction, generated code, and many other practices that make code non-self-documenting. What can I learn from a line like "set objTemp = getData(i,j,k)"? Only that I need to go analyze getData(), and anything it calls before I can figure out whether this call is even relevant to the bug I am trying to track down.
Continued next post... (If this comment was disrespectful, please report it.)
The problem is exacerbated by poorly structured code, poor naming, and poor external documentation, all of which tend to go along with poor commenting.
Comments are the easiest thing to get right, and will make correction of the other problems easier to correct.
It is infuriating to spend 30 minutes to analyze something that someone else could have commented in 10 seconds.
Is Mr. Webb a "big fish in a small pond"? Has he forgotten what it it is like to come to an application cold? (If this comment was disrespectful, please report it.)
Thanks for the feedback. I agree with your view points. As I have also stated, some people (Mr. Webb for example) take to there own standards as a religion. However, I'm still keeping an open mind and always learning to how I can code better for others that may come after me on my projects. (If this comment was disrespectful, please report it.)
I work as a programmer at a local engineering firm and at 3PM today I was instructed to make a script that would take ppls contact info and store it in a DB, and email the new contacts info. If the contact was already registered do a login type procedure. Then after that it would give a quote on an engineering product from this company. I used all of the LEWIS-STYLE programming and learned ASP from 3PM to 6PM and the script was done by 6:30 thanks d00d (If this comment was disrespectful, please report it.)
1/25/2005 5:56:34 PM:
I found this article illuminating. I've been using other languages, just moved over to ASP, and it's great to see some Common Practices. One question: I came here to learn about garbage collection. I'd love to know the reasoning behind the (If this comment was disrespectful, please report it.)
1/25/2005 5:58:02 PM:
(continued from previous post... dont use double-quotes) set obj = nothing statement. My guess is that any variable that goes out of scope will automatically release its object. If this is true, what scenarios would need an explicit =nothing statement? Also, what benefits does always explicitly releasing objects give? I'm looking to find out how helpful this standard is, and when it's needed. Again, thanks for the article. (If this comment was disrespectful, please report it.)
only one word bout this dude -AWESOME- (If this comment was disrespectful, please report it.)
Add Your Feedback
Your feedback will be posted below and an email sent to
the author. Please remember that the author was kind enough to
share this with you, so any criticisms must be stated politely, or they
will be deleted. (For feedback not related to this particular article, please
click here instead.)