You will be redirected in 30 seconds or close now.

ColdFusion Authors: Yakov Fain, Jeremy Geelan, Maureen O'Gara, Nancy Y. Nee, Tad Anderson

Related Topics: ColdFusion

ColdFusion: Article

Best Practices in ColdFusion Development

Best Practices in ColdFusion Development

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.

General 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">
<cftransaction action="commit">

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:

<cfoutput>DBCustomers#RandRange (1,1999999999)#

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:

  1. In the Resource window navigate to your project folder.
  2. Right-click in the file list.
  3. Choose "favorite folders > Add current folder to favorites". Add your folder.
  4. 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
I hope there are one or two suggestions among these that seasoned developers haven't explored and can try out on their own. I also hope beginning coders have found that even if you don't follow any of the suggestions outlined here, it's time saving and aggravation reducing to create a set of your own coding practices that you stick to consistently.

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.

More Stories By Eben Hewitt

Eben Hewitt is a Web application developer for Canyon WebWorks-Arizona Internet, the largest full-service Internet company in the state, and an Allaire Alliance Consulting and Hosting Partner. Eben has been writing ColdFusion applications for a more than a year. He has a master’s degree, though he hopes no one will hold it against him.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.

@ThingsExpo Stories
Nordstrom is transforming the way that they do business and the cloud is the key to enabling speed and hyper personalized customer experiences. In his session at 21st Cloud Expo, Ken Schow, VP of Engineering at Nordstrom, will discuss some of the key learnings and common pitfalls of large enterprises moving to the cloud. This includes strategies around choosing a cloud provider(s), architecture, and lessons learned. In addition, he’ll go over some of the best practices for structured team migrat...
SYS-CON Events announced today that Taica will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Taica manufacturers Alpha-GEL brand silicone components and materials, which maintain outstanding performance over a wide temperature range -40C to +200C. For more information, visit http://www.taica.co.jp/english/.
SYS-CON Events announced today that MIRAI Inc. will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. MIRAI Inc. are IT consultants from the public sector whose mission is to solve social issues by technology and innovation and to create a meaningful future for people.
Recently, REAN Cloud built a digital concierge for a North Carolina hospital that had observed that most patient call button questions were repetitive. In addition, the paper-based process used to measure patient health metrics was laborious, not in real-time and sometimes error-prone. In their session at 21st Cloud Expo, Sean Finnerty, Executive Director, Practice Lead, Health Care & Life Science at REAN Cloud, and Dr. S.P.T. Krishnan, Principal Architect at REAN Cloud, will discuss how they bu...
Coca-Cola’s Google powered digital signage system lays the groundwork for a more valuable connection between Coke and its customers. Digital signs pair software with high-resolution displays so that a message can be changed instantly based on what the operator wants to communicate or sell. In their Day 3 Keynote at 21st Cloud Expo, Greg Chambers, Global Group Director, Digital Innovation, Coca-Cola, and Vidya Nagarajan, a Senior Product Manager at Google, will discuss how from store operations...
As hybrid cloud becomes the de-facto standard mode of operation for most enterprises, new challenges arise on how to efficiently and economically share data across environments. In his session at 21st Cloud Expo, Dr. Allon Cohen, VP of Product at Elastifile, will explore new techniques and best practices that help enterprise IT benefit from the advantages of hybrid cloud environments by enabling data availability for both legacy enterprise and cloud-native mission critical applications. By rev...
Join IBM November 1 at 21st Cloud Expo at the Santa Clara Convention Center in Santa Clara, CA, and learn how IBM Watson can bring cognitive services and AI to intelligent, unmanned systems. Cognitive analysis impacts today’s systems with unparalleled ability that were previously available only to manned, back-end operations. Thanks to cloud processing, IBM Watson can bring cognitive services and AI to intelligent, unmanned systems. Imagine a robot vacuum that becomes your personal assistant tha...
SYS-CON Events announced today that Datera will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Datera offers a radically new approach to data management, where innovative software makes data infrastructure invisible, elastic and able to perform at the highest level. It eliminates hardware lock-in and gives IT organizations the choice to source x86 server nodes, with business model option...
With major technology companies and startups seriously embracing Cloud strategies, now is the perfect time to attend 21st Cloud Expo October 31 - November 2, 2017, at the Santa Clara Convention Center, CA, and June 12-14, 2018, at the Javits Center in New York City, NY, and learn what is going on, contribute to the discussions, and ensure that your enterprise is on the right path to Digital Transformation.
Infoblox delivers Actionable Network Intelligence to enterprise, government, and service provider customers around the world. They are the industry leader in DNS, DHCP, and IP address management, the category known as DDI. We empower thousands of organizations to control and secure their networks from the core-enabling them to increase efficiency and visibility, improve customer service, and meet compliance requirements.
Digital transformation is changing the face of business. The IDC predicts that enterprises will commit to a massive new scale of digital transformation, to stake out leadership positions in the "digital transformation economy." Accordingly, attendees at the upcoming Cloud Expo | @ThingsExpo at the Santa Clara Convention Center in Santa Clara, CA, Oct 31-Nov 2, will find fresh new content in a new track called Enterprise Cloud & Digital Transformation.
SYS-CON Events announced today that N3N will exhibit at SYS-CON's @ThingsExpo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. N3N’s solutions increase the effectiveness of operations and control centers, increase the value of IoT investments, and facilitate real-time operational decision making. N3N enables operations teams with a four dimensional digital “big board” that consolidates real-time live video feeds alongside IoT sensor data a...
SYS-CON Events announced today that NetApp has been named “Bronze Sponsor” of SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. NetApp is the data authority for hybrid cloud. NetApp provides a full range of hybrid cloud data services that simplify management of applications and data across cloud and on-premises environments to accelerate digital transformation. Together with their partners, NetApp emp...
Smart cities have the potential to change our lives at so many levels for citizens: less pollution, reduced parking obstacles, better health, education and more energy savings. Real-time data streaming and the Internet of Things (IoT) possess the power to turn this vision into a reality. However, most organizations today are building their data infrastructure to focus solely on addressing immediate business needs vs. a platform capable of quickly adapting emerging technologies to address future ...
SYS-CON Events announced today that Avere Systems, a leading provider of hybrid cloud enablement solutions, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Avere Systems was created by file systems experts determined to reinvent storage by changing the way enterprises thought about and bought storage resources. With decades of experience behind the company’s founders, Avere got its ...
SYS-CON Events announced today that Avere Systems, a leading provider of enterprise storage for the hybrid cloud, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Avere delivers a more modern architectural approach to storage that doesn't require the overprovisioning of storage capacity to achieve performance, overspending on expensive storage media for inactive data or the overbui...
SYS-CON Events announced today that IBM has been named “Diamond Sponsor” of SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California.
SYS-CON Events announced today that Ryobi Systems will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Ryobi Systems Co., Ltd., as an information service company, specialized in business support for local governments and medical industry. We are challenging to achive the precision farming with AI. For more information, visit http:...
High-velocity engineering teams are applying not only continuous delivery processes, but also lessons in experimentation from established leaders like Amazon, Netflix, and Facebook. These companies have made experimentation a foundation for their release processes, allowing them to try out major feature releases and redesigns within smaller groups before making them broadly available. In his session at 21st Cloud Expo, Brian Lucas, Senior Staff Engineer at Optimizely, will discuss how by using...
In this strange new world where more and more power is drawn from business technology, companies are effectively straddling two paths on the road to innovation and transformation into digital enterprises. The first path is the heritage trail – with “legacy” technology forming the background. Here, extant technologies are transformed by core IT teams to provide more API-driven approaches. Legacy systems can restrict companies that are transitioning into digital enterprises. To truly become a lead...