|By Eben Hewitt||
|January 27, 2001 12:00 AM EST||
In recent years we've witnessed a trend in which organizations gather, codify, evaluate, and disseminate seemingly endless lists of "Best Practices" - guidelines that help promote the success of their business, the consistency of their actions and, presumably, the general cheerfulness of their employees.
Best Practices are cherished by neophytes and mentors alike for many reasons. For beginners (or those toiling fiendishly into the night, alone in their basements, who can't help but cackle, "It's alive!" every time their application runs without crashing), Best Practices offer a coherent and consistent mode of communication with fellow coders who might inherit their work. They also offer guidelines that hasten the debugging process, and they create a compendium of development tips and tricks that can be time consuming to find on your own. For more seasoned developers, Best Practices offer a refreshing prompt to review their habits - as Hal Helms suggested in "Making Assertions" (CFDJ, Vol. 2, issue 10) - and provide an excellent excuse for engaging in witty and urbane debate with one's peers.
These particular Best Practices are divided into five categories: General, Security, Portability/Modularity, Speed/Performance, and Teamwork/Readability. In the spirit of pursuing a provocative American trend, I offer this list of Best Practices for ColdFusion coding and development, which is the strange fruit of many conversations with many developers. My hope is to continue that conversation, and I invite your responses as well as your own Best Practices.
When debugging an application, set a simple variable and use <cfoutput> to display it on your processing page.
For instance, you might write <cfset Status = "Okay"> in the offending template, then write <cfoutput>#Status#</cfoutput> in the page in question. If you see the word "Okay" when you view your page in a browser, ColdFusion is processing your application at least up to that point. Move the <cfoutput> tags around within your application, and you can pinpoint exactly how far your application is processing, de-pending on whether or not your output is displayed.
This is also a good way to ensure compatibility of your applications across browsers. For instance, Internet Explorer 5.5 handles table display differently than IE 5.0 does. I've seen well-written applications that simply don't display in IE 5.5. This tip was the light at the end of the tunnel.
You can use a related technique within <cftransaction> blocks. For instance, set the status variable as above, and write a conditional clause around your <cftransaction> <cfquery> block. Set the status to "Not Okay" within a <cfcatch/cftry> block where the <cftransaction> is "Rollback".
<cfif status IS "Okay">
Your output will indicate the status of your database transaction.
Use the poor man's Spectra.
While this little idea certainly doesn't cover the many excellent features of Spectra, doing the following will help keep your clients - or your non-IT staff - happy when frequent content updates are an issue. Use a custom tag for formatting and general page display, and <cfinclude> all your content. For instance, when working on a page called "Aboutus.cfm", you might create a custom tag called <cf_layout> or <cf_table>, which allows easy and consistent specification of its attri-butes. You can title the headers of your tables, specify the colors and borders, and size them up. Then write a file called "AboutusContent.cfm", which is only plain text and no code. In a cell within your table call <cfinclude template= "Aboutus Content.cfm">. You can specify fonts with an external stylesheet or from within your custom tag, and you've got instant, consistent formatting and total separation of code from content. When it's time for others to update the content, they don't touch a line of code. Note that there's a slight performance penalty for using <cfinclude> as well as for any custom tag.
<td align="right"><font face=#font#" size=#medsize#">
</td><input type="Text" name="Username" size="#bigsize#"></td></cfoutput>
where the file LogoTable.cfm de-fines the fonts and sizes as cfparameters and also begins the table by defining a <tr> that contains the company logo, a background color, and more. It's a way of making a hybrid stylesheet/HTML that's easy to reuse.
You can also easily borrow Spectra's Universally Unique Identifier for Content Objects with the ColdFusion "CreateUUID" function as follows: <cfoutput>#CreateUUID()# </cfoutput>. It's also native to Transact-SQL as "NewID()". They both generate a 128-bit value, (almost) guar-anteed to be a unique value for any computer on a network because the last six digits are generated from the node number for the IEEE 802 identifier on your machine's NIC. Kewl! (Notice that there are a couple dozen CF functions like this one that have an exact counterpart in SQL. Use the CF functions when possible, however, for reasons that follow.)
Always scope your variables.
Perhaps it's a little thing, but I've found that referring to #Form.My Variable# rather than #MyVariable# makes it easier for other developers to follow your work, and it cuts down on debugging time. As a side note, remember that when working with <cfmodule>, the code of the module or custom tag is executed in its own process, outside the scope of the calling template. (Thus the module has no access to variables in the calling template.)
Don't use hidden fields to pass any sensitive or important variable (e.g., "price" or a limitation on record set returns).
While it's less of a problem with ColdFusion, it takes seconds to hack a page written in Perl or any CGI/server-side language that passes hidden form field variables. (Hacking 101: simply save the page source as an htm file, change the hidden variable to a price or limitation you like better, and pass your new local page to the absolute URL of the processing page.)
In guest book or other form, don't allow *<CF* as user input.
User input forms allow what my wife refers to as an "attractive nuisance"; hooligans have an opportunity to run code (cfdirectory, cffile) from your text fields. Make sure your application knows to return a tsk-tsk if it spots such input. Check for this by placing the following code at the top of your processing page:
<cfif Form.TextBody CONTAINS "%<cf%">
<cfabort showerror="You are very naughty.">
Thanks for your input. Etc...
Note that <cfexit> is a better choice than <cfabort> if you're running a custom tag.
Use the poor woman's dedicated SQL server.
You've heard it a hundred times. Put your databases on a different machine. But many maverick developers are unable to afford such a scheme. If you're in this valiant group, there is recourse. At the least make sure your databases aren't in the HTTP tree. If you have no control over this (if you're not hosting yourself), generate a random number to name your database with the following code:
If you do have a separate database machine and Web server but one is more powerful than the other, let the faster one be your SQL server. The sine qua non of many ColdFusion applications is a database; therefore, slow database = slow CFServer, but not the other way around.
Avoid proliferating <cfauthenticate> tags since you must specify the security context on the server.
If you move your app to another host or plug the module into an application on a host out of your control or reinstall ColdFusion server or make a significant upgrade, you'll likely have to rewrite your security context, forcing a potentially difficult migration. If you don't face these dilemmas, <cfauthenticate> is an otherwise handy tag.
Format data within your code, not your SQL data type.
For example, imagine you have a field named "Price". Rather than specifying the datatype "money" in your SQL database, specify INT and use the ColdFusion function Dollar format(#Price#). This practice allows you to follow the tradition that dictates one must separate display, action, and content. Also at issue here is portability/migration between database versions and database vendors. This may be more useful to independent developers looking to peddle their application wares than to job shops with their hosting routine down. Note that you'll take a slight performance hit in the (potentially lengthy) interim.
Use relative paths.
In the root of your applications create a folder called "files" or "general" to store single-page items such as "about" and "contactus" that may not merit an entire folder to themselves. Putting all pages in directories off the root maintains the relative paths for <cfincludes>, images, and Flash menu actions (such as GetURL). If you develop for a number of different clients, it's easy to move an application (or part of one) or reuse the entire app in another site. It makes later additions and changes easier to implement and gives you greater control of definitions and permissions in your Web server.
Refrain from running <cfloop>s and other complex logic within your <cfquery> tags.
Because the driver connection remains open for the duration of the code executing within <cfquery> tags, Allaire recommends keeping the executable code therein to a minimum. Anyway, you can accomplish the same task by separating out conditional queries to be run only in the event of a <cfswitch/case> clause as in Fusebox. This reduces to: never hit the database if you don't have to, never ask the database for one column or one row more than you need, and keep your conditional logic in Coldfusion where it belongs.
If database performance is an issue for you, keep this in mind: when designing your tables, accept NULL values sparingly, if at all. SQL Server stores a bitmap in every row to indicate whether a column set to accept NULL values is indeed NULL. By allowing NULLs you force SQL Server to decode this bitmap in each and every called row. This practice multiplies the complexity (read "proneness to bugs") of an application. The server logic em-ployed earns you a second performance penalty as well, as you must account for the allowed values throughout your code.
If you have more than one iteration of the <cfif, cfelseif, and cfelse> tag group, consider using <cfswitch> and <cfcase> to boost performance. In a <cfif/cfelse> scenario, ColdFusion must test against every condition before exiting the clause. If your expression matches the final condition in your series of if/elses, ColdFusion is forced to test and reject every condition. Switch/case is less code text than <cfif/cfelse>, making it easier to follow and debug, and since the conditional logic is more efficient, you can take home a performance boost.
Use nested <cfif> tags sparingly.
I state this as a corollary to the above, though the larger point has been made.
Use the function GetTickCount for testing slow or crashing templates implementing CFX tags or complex CFML logic to isolate the source of the problem.
GetTickcount returns a millisecond counter for timing the processing of ColdFusion markup. Try running the following example code. If this page returns slowly in a no-load environment, you can be confident your performance problem is server side and not due to poor coding or conditional logic. Then test it in a loaded environment, such as the suspect template, where your problem will be exacerbated.
<CFSET Count = 1000>
<CFLOOP Index = idxMyIndex From=1>
<CFSET Start = GetTickCount()>
<CFSET Stop = GetTickCount()>
<CFSET RoundTripTime = Stop - Start>
<CFOUTPUT>Round Trip time was #RoundTripTime# milliseconds</CFOUTPUT>
For Spectra developers, watch this count spiral past 3,000. Then have a heart to heart with your sys admin. (Remember, too, that the IIS 4 Management Console spawns a memory leak if left running. Windows 2000's IIS 5 sports a memory leak so exuberant that it will crash your entire system if you don't run the recently released service pack.)
Trick ColdFusion Studio into quickly saving files in your current project folder, rather than the default Studio folder, for speedy development.
Create a favorite with the following steps:
- In the Resource window navigate to your project folder.
- Right-click in the file list.
- Choose "favorite folders > Add current folder to favorites". Add your folder.
- Your subsequent effort to File > Save should result in your folder opening first.
Use lots of comments.
Everyone says this, but the resulting comments from such a vaguely stated rule are vague enough themselves. More important, who hasn't been set back days or weeks by poorly (or un-) commented code they've inherited? Coders must leave breadcrumbs, especially in a landscape where people typically stay at a job for no more than six months. In your application.cfm file, note the following: the author name and e-mail, the date, and a description of the application. As Ben Forta writes in "'The Ten Commandments' - Revisted" (CFDJ, Vol. 2, issue 10), "...every conditional statement, every loop, every set of variable assignments, and every include or component reference, must be commented with a simple statement explaining what's being done, and why."
To this I'd add that you note at the top of your list what other processes are dependent on the current process. This way, if I cut anything out of my app elsewhere, you'll be able to tell what else might unexpectedly fall apart. I even go so far as to include a "ReadMe.cfm" file in every application I write. When you comment heavily like this, however, I suggest you get rid of the resulting whitespace. In ColdFusion 4.5 you can do this by going to the Administration Page and enabling "Suppress whitespace by default". Refrain from ending a template with a comment if you choose this setting on the server. On a local level, you can also use the <cfprocessingdirective suppresswhitespace="Yes"> tag to handle it. The downside? You need this tag and its closing counterpart in all the templates you have to remove the spaces.
Use tab stops in your code to make it readable later - for yourself and others.
Validate at the top of the form so you can immediately see which fields contain a validation rule.
Use a standard, conventional nomenclature for your ColdFusion objects.
The Hungarian notation standard used in constructing Visual Basic and C applications offers some direction (see Table 1). So named because it was popularized at Microsoft by Hungarian programmer Charles Simonyi, Hungarian notation is a naming convention that allows the programmer to determine the type and use of an identifier (variable, function, constant, etc.)
If you don't like Hungarian notation, just make one up with the people on your team - and consider the following:
- Mnemonic value: Makes it easy to remember the name
- Suggestive value: So others can easily understand the name
- Consistency: Similar names for similar objects
Thank you to everyone who contributed suggestions, especially to Ben Forta for pointing me in good directions for research, and to my friend and colleague Garrick Brooks for contributing excellent ideas on security issues.
- Where Are RIA Technologies Headed in 2008?
- The Next Programming Models, RIAs and Composite Applications
- AJAX World RIA Conference & Expo Kicks Off in New York City
- Constructing an Application with Flash Forms from the Ground Up
- Building a Zip Code Proximity Search with ColdFusion
- Personal Branding Checklist
- CFEclipse: The Developer's IDE, Eclipse For ColdFusion
- Has the Technology Bounceback Begun?
- Cloud People: A Who's Who of Cloud Computing
- i-Technology Viewpoint: We Need Not More Frameworks, But Better Programmers
- Adobe Flex 2: Advanced DataGrid
- Web Services Using ColdFusion and Apache CXF