Comment Your Code

Perhaps the most important step in programming that almost all developers overlook, either because of lack of time or for other reasons, is that of commenting their code. What exactly does commenting your code mean? It means that you take each chunk of code, each module, each variable, each tricky workaround, and so forth and describe its purpose, catches, caveats, and so on in detail. You provide this information in the code itself, using the comment tag (hence, "commenting") of the language you're using to basically tell the story of how your code works. You should comment everything. Everything. Can we say it again? Everything.

start sidebar
Some "Standard" Comment Tag Structures

Almost all programming languages have a comment tag or statement of some sort. A statement or a symbol tells the code compiler or code interpreter to ignore the text that follows, since it won't be used as part of the actual code. Many programming languages, HTML included, have in-line comment and block comment tags. In-line comments can be included within a line of code. A block comment "blocks off" chunks of text within the code.Here are some of the more familiar comment tags you will encounter. (We've included Pascal simply because it is the first language many beginning programmers learn.)

HTML

Inline Comment Marker:
n/aOpening Block: <!--
Closing Block: -->

ColdFusion

Inline Comment Marker:
n/aOpening Block: <!---
Closing Block: --->

ASP

Inline Comment Marker: '
Opening Block: n/a
Closing Block: n/a

Pascal

Inline Comment Marker: ;
Opening Block: /*
Closing Block: */

PHP

Inline Comment Marker: // OR #
Opening Block: /*
Closing Block:*/

MySQL

Inline Comment Marker: #
Opening Block: /*
Closing Block: */

Microsoft SQL Server

Inline Comment Marker: --
Opening Block: /*
Closing Block: */

end sidebar

Document your code just as if you were telling a friend how to get to your new house. Mention everything that could even remotely be considered important because you are creating a roadmap that explains why you created the code in the way you did, what the variables do, and the purpose of the code. Remember, even though you have all this detailed information about your code in your head right now, you probably won't remember it a year from now. And, invariably, you'll need to modify code in a system at some point as your organization's needs change.

start sidebar
The First Commenting Rule of Thumb: Comment As You Go

Comment your code as you write it. Comment your design as you build it. Even though you may be on a roll and cranking out code faster than you ever have before, you still need to comment as you go. If you don't, chances are, you won't come back and do it later. In fact, even if you do come back to it, you'll probably take more time going back because you'll have to "relearn" what your code does in order to create accurate comments. Save time and effort and plan for the future by commenting as you go.line

end sidebar

A few guidelines follow regarding commenting your code.

Create a Boilerplate Header Comment

Every page, function, and routine should include a comment structure that describes the page, function, or routine, gives its purpose, and so on. Developers like to include different information in the header comment such as variable purpose, time of last modification, and so forth. Create a comment boilerplate that fits your organization's needs while giving enough detail to explain your code. Then, make sure you include it at the top of at least every new file, if not every function and routine. A sample web page boilerplate header might look like the following:

<!-------------------------------------------------------  System: Ad-banner display system   File:   /lib/include/GetUserInformation.asp  Client: SybexCreated  by:     Darren McGee Date Created: 8/9/2002   Last Modified: 9/6/2002  Purpose:       Gets all the information for a given user, including the ads     viewed, the clicks made, and user type History:   08/10/2002 - jdm - added password verification            08/20/2002 - mhk - modified table display to 800x600 specs            08/30/2002 - jdm - fixed pre-version-4 browser display bug Calling pages:  DisplayUserInfo.asp; DisplayAllInfo.asp;  Called pages:   CalculatePageview.asp Variables: nClick - number of clicks on a particular link            aUser - array containing user information -------------------------------------------------------------------->

This sample contains a lot of information. Although providing this information does take time away from your coding , you can quickly and easily tell from the comment header what the file's purpose is, which files call it, which files it calls, and the history of changes to the file. Naturally, you'll want to customize such a header to suit your needs, but we recommend that you make it part of your standard program template. That way, whenever you create a new program file, the header will be automatically placed for you-all you have to do is change the appropriate information.

Tip 

Tip You can save files as templates within Dreamweaver MX by choosing File ® Save As Template. If you want to modify a template that Dreamweaver MX provides, open it as a new file, make your comment header changes, and then save the template with a new name.

Comment the Variables

You wouldn't get far in code development without the use of variables. We use variables to make our web pages and other code dynamic, since we can store information in variables, manipulate them, and delete them as we need. They're flexible and obviously handy to have around. But have you ever tried to debug someone else's code in which the variables weren't well documented? Trying to determine what purpose unknown variables serve can be a time-consuming puzzle, so comment every variable you use in the function or page you're creating. Regardless of whether you define the variables in the comment header, definitely add a comment describing the variable after its declaration. For example, the following snippet shows a few variables that without the defining comment would otherwise be obscure:

Dim intPlayerID    'Player ID Number  Dim strPlayer    'Player's full name  Dim lIsCaptain    'Logical for the captain?  Dim strTeamID    'Used to store Team ID Number  Dim strTeamName    'Used to store Team Name  Dim bHasCaptain    'Used to determine if team has a captain  Dim strStates    'Used as a full length string to populate state drop down  Dim intNewID    'Used to capture new player ID

Comment Chunks of Code That Perform a Particular Task

In addition to adding a header comment and commenting your variables, also comment chunks of code that perform a particular task. That is, comment chunks of code that work together within the same page. For example, as you can see in the following code snippet, the developer pointed out the code used for validation and gave a few notes about how it works.

Dim cnStreetball Set cnStreetball = Server.CreateObject("ADODB.Connection")  cnStreetball.ConnectionString = Application("cnStreetball_ConnectionString") cnStreetball.Open '========================================================   ' Validation  '=======================================================  ' IsAdmin overrides team check  ' Use the passed Team ID and check it against the  stored cookie.  '================================  If Not IsAdmin() Then   If NOT Validate(strTeamID, Request. Cookies("streetballshowdown")   ("teampwd"),2) Then      Response.Redirect "TeamLogin.asp"   End IF End If If Request.Form("action") = "1" Then     '// Perform an Update    '// If a PlayerID exists then update;else Insert    If Len (Trim(intPlayerID)) = 0 Then       '//Perform an Insert       intNewID = InsertPlayer        If intNewID > 0 Then          Response.Redirect "Team.asp?TeamID=          " & strTeamID & "&TeamName=" & Server.URLEncode(strTeamName)    Else       Response.Write "An insert error has occurred. Please   contact a system administrator."      End If  Else   '// Perform an Update

In this snippet, the developer chose to make the comments stand out a bit more from the code by using a double-slash (//) after the comment marker. Since comments can be hard to separate from code on a black-and-white printout, you may find this a good idea to adopt.

This code snippet also demonstrates a method of commenting that causes some controversy-the "clutter" comment used to separate the comment from other lines of code. Some developers and development companies suggest that you separate comments with chunks of white space. Frankly, we feel it doesn't have the same effect, as you can see by the modified snippet that follows. We suggest that you use whatever works best for you, your aesthetic tastes, and your work environment. But whichever style you choose, be consistent.

Set cnStreetball = Server.CreateObject("ADODB.Connection")  cnStreetball.ConnectionString = Application("cnStreetball_ConnectionString")  cnStreetball.Open ' Validation  '  ' IsAdmin overrides team check  ' Use the Passed Team ID and Check it with the Cookie. If Not IsAdmin() Then    If NOT Validate(strTeamID,     Request.Cookies("streetballshowdown")("teampwd"),2) Then       Response.Redirect "TeamLogin.asp"

General Comments about Commenting

There are numerous commenting methods and numerous commenting styles, and, of course, there is the lack of commenting. Developers don't like to do it, but they must if they want to maintain a clean, consistent, informative code design. Make commenting one of your standard practices, if you don't already.

Here are a few other guidelines regarding commenting.

  • Comment anything that isn't readily understood or that might generate a question for developers modifying your code in the future.

  • Comment control structures such as logic controls, loops, and other items that could take the logic flow in different directions.

  • Make sure your comments are simple, clear, meaningful, and precise. We recommend you use complete sentences, since doing so helps force you to comment clearly and prevent ambiguity.

  • You don't need to comment every line in the code. Comments should explain what your intention is for the code and what a particular code chunk does-not act as a translator for every statement you created.

  • You might want to develop a few keywords to use in your comments that alert other developers to particularly important items. For example, you might want to use TRICKY for a piece of code that is complex to warn other developers to be careful when modifying it. Or you might use KLUDGY to indicate code that is a bit sloppy and needs to be improved. (You shouldn't be creating sloppy code at all, but sometimes time constraints don't let every developer generate the most elegant piece of code ever created. Sometimes, in today's business world, we have to get it done and then go back and make it elegant.)

  • When you're editing your code, update your comments appropriately. You don't want to revisit the code seven months later to find that the code behaves nothing like its comments say it should.

  • Generally, you do not want to put comments at the end of a line of code-except for variable declarations-because end-of-line comments are difficult to read and probably will end up wrapping in your code editor.

  • Before you actually post the code on your production server, make sure your comments are clean and clear. Remove any superfluous or temporary comments that don't shed light on the code's purpose. Yes, this means erase the humorous comments you might have added about the design of the code or your boss's attitude.



Mastering Dreamweaver MX Databases
Mastering Dreamweaver MX Databases
ISBN: 078214148X
EAN: 2147483647
Year: 2002
Pages: 214

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net