Welcome!

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

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">
<cfquery...></cfquery></cfif></cftransaction>

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.

<cf_LogoTable>
<tr><cfoutput>
<td align="right"><font face=#font#" size=#medsize#">
Username:</font></td>
</td><input type="Text" name="Username" size="#bigsize#"></td></cfoutput>
</tr>
</cf_Logotable>

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.)

Security
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.">
<cfelse>
Thanks for your input. Etc...
</cfif>

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)#
</cfoutput>

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.

Portability/Modularity
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.

Speed/Performance
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()>
To=#Count#></CFLOOP>
<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.
Teamwork/Readability
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
The major cloud platforms defy a simple, side-by-side analysis. Each of the major IaaS public-cloud platforms offers their own unique strengths and functionality. Options for on-site private cloud are diverse as well, and must be designed and deployed while taking existing legacy architecture and infrastructure into account. Then the reality is that most enterprises are embarking on a hybrid cloud strategy and programs. In this Power Panel at 15th Cloud Expo (http://www.CloudComputingExpo.com), moderated by Ashar Baig, Research Director, Cloud, at Gigaom Research, Nate Gordon, Director of T...
The definition of IoT is not new, in fact it’s been around for over a decade. What has changed is the public's awareness that the technology we use on a daily basis has caught up on the vision of an always on, always connected world. If you look into the details of what comprises the IoT, you’ll see that it includes everything from cloud computing, Big Data analytics, “Things,” Web communication, applications, network, storage, etc. It is essentially including everything connected online from hardware to software, or as we like to say, it’s an Internet of many different things. The difference ...

ARMONK, N.Y., Nov. 20, 2014 /PRNewswire/ --  IBM (NYSE: IBM) today announced that it is bringing a greater level of control, security and flexibility to cloud-based application development and delivery with a single-tenant version of Bluemix, IBM's platform-as-a-service. The new platform enables developers to build ap...

Cloud Expo 2014 TV commercials will feature @ThingsExpo, which was launched in June, 2014 at New York City's Javits Center as the largest 'Internet of Things' event in the world.
An entirely new security model is needed for the Internet of Things, or is it? Can we save some old and tested controls for this new and different environment? In his session at @ThingsExpo, New York's at the Javits Center, Davi Ottenheimer, EMC Senior Director of Trust, reviewed hands-on lessons with IoT devices and reveal a new risk balance you might not expect. Davi Ottenheimer, EMC Senior Director of Trust, has more than nineteen years' experience managing global security operations and assessments, including a decade of leading incident response and digital forensics. He is co-author of t...
Explosive growth in connected devices. Enormous amounts of data for collection and analysis. Critical use of data for split-second decision making and actionable information. All three are factors in making the Internet of Things a reality. Yet, any one factor would have an IT organization pondering its infrastructure strategy. How should your organization enhance its IT framework to enable an Internet of Things implementation? In his session at Internet of @ThingsExpo, James Kirkland, Chief Architect for the Internet of Things and Intelligent Systems at Red Hat, described how to revolutioniz...
Technology is enabling a new approach to collecting and using data. This approach, commonly referred to as the "Internet of Things" (IoT), enables businesses to use real-time data from all sorts of things including machines, devices and sensors to make better decisions, improve customer service, and lower the risk in the creation of new revenue opportunities. In his General Session at Internet of @ThingsExpo, Dave Wagstaff, Vice President and Chief Architect at BSQUARE Corporation, discuss the real benefits to focus on, how to understand the requirements of a successful solution, the flow of ...
The security devil is always in the details of the attack: the ones you've endured, the ones you prepare yourself to fend off, and the ones that, you fear, will catch you completely unaware and defenseless. The Internet of Things (IoT) is nothing if not an endless proliferation of details. It's the vision of a world in which continuous Internet connectivity and addressability is embedded into a growing range of human artifacts, into the natural world, and even into our smartphones, appliances, and physical persons. In the IoT vision, every new "thing" - sensor, actuator, data source, data con...
"BSQUARE is in the business of selling software solutions for smart connected devices. It's obvious that IoT has moved from being a technology to being a fundamental part of business, and in the last 18 months people have said let's figure out how to do it and let's put some focus on it, " explained Dave Wagstaff, VP & Chief Architect, at BSQUARE Corporation, in this SYS-CON.tv interview at @ThingsExpo, held Nov 4-6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
Focused on this fast-growing market’s needs, Vitesse Semiconductor Corporation (Nasdaq: VTSS), a leading provider of IC solutions to advance "Ethernet Everywhere" in Carrier, Enterprise and Internet of Things (IoT) networks, introduced its IStaX™ software (VSC6815SDK), a robust protocol stack to simplify deployment and management of Industrial-IoT network applications such as Industrial Ethernet switching, surveillance, video distribution, LCD signage, intelligent sensors, and metering equipment. Leveraging technologies proven in the Carrier and Enterprise markets, IStaX is designed to work ac...
"There is a natural synchronization between the business models, the IoT is there to support ,” explained Brendan O'Brien, Co-founder and Chief Architect of Aria Systems, in this SYS-CON.tv interview at the 15th International Cloud Expo®, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
C-Labs LLC, a leading provider of remote and mobile access for the Internet of Things (IoT), announced the appointment of John Traynor to the position of chief operating officer. Previously a strategic advisor to the firm, Mr. Traynor will now oversee sales, marketing, finance, and operations. Mr. Traynor is based out of the C-Labs office in Redmond, Washington. He reports to Chris Muench, Chief Executive Officer. Mr. Traynor brings valuable business leadership and technology industry expertise to C-Labs. With over 30 years' experience in the high-tech sector, John Traynor has held numerous...
Bit6 today issued a challenge to the technology community implementing Web Real Time Communication (WebRTC). To leap beyond WebRTC’s significant limitations and fully leverage its underlying value to accelerate innovation, application developers need to consider the entire communications ecosystem.
The 3rd International @ThingsExpo, co-located with the 16th International Cloud Expo - to be held June 9-11, 2015, at the Javits Center in New York City, NY - announces that it is now accepting Keynote Proposals. The Internet of Things (IoT) is the most profound change in personal and enterprise IT since the creation of the Worldwide Web more than 20 years ago. All major researchers estimate there will be tens of billions devices - computers, smartphones, tablets, and sensors - connected to the Internet by 2020. This number will continue to grow at a rapid pace for the next several decades.
The Internet of Things is not new. Historically, smart businesses have used its basic concept of leveraging data to drive better decision making and have capitalized on those insights to realize additional revenue opportunities. So, what has changed to make the Internet of Things one of the hottest topics in tech? In his session at @ThingsExpo, Chris Gray, Director, Embedded and Internet of Things, discussed the underlying factors that are driving the economics of intelligent systems. Discover how hardware commoditization, the ubiquitous nature of connectivity, and the emergence of Big Data a...
Almost everyone sees the potential of Internet of Things but how can businesses truly unlock that potential. The key will be in the ability to discover business insight in the midst of an ocean of Big Data generated from billions of embedded devices via Systems of Discover. Businesses will also need to ensure that they can sustain that insight by leveraging the cloud for global reach, scale and elasticity.
SYS-CON Events announced today that Windstream, a leading provider of advanced network and cloud communications, has been named “Silver Sponsor” of SYS-CON's 16th International Cloud Expo®, which will take place on June 9–11, 2015, at the Javits Center in New York, NY. Windstream (Nasdaq: WIN), a FORTUNE 500 and S&P 500 company, is a leading provider of advanced network communications, including cloud computing and managed services, to businesses nationwide. The company also offers broadband, phone and digital TV services to consumers primarily in rural areas.
SYS-CON Events announced today that IDenticard will exhibit at SYS-CON's 16th International Cloud Expo®, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. IDenticard™ is the security division of Brady Corp (NYSE: BRC), a $1.5 billion manufacturer of identification products. We have small-company values with the strength and stability of a major corporation. IDenticard offers local sales, support and service to our customers across the United States and Canada. Our partner network encompasses some 300 of the world's leading systems integrators and security s...
IoT is still a vague buzzword for many people. In his session at @ThingsExpo, Mike Kavis, Vice President & Principal Cloud Architect at Cloud Technology Partners, discussed the business value of IoT that goes far beyond the general public's perception that IoT is all about wearables and home consumer services. He also discussed how IoT is perceived by investors and how venture capitalist access this space. Other topics discussed were barriers to success, what is new, what is old, and what the future may hold. Mike Kavis is Vice President & Principal Cloud Architect at Cloud Technology Pa...
Cloud Expo 2014 TV commercials will feature @ThingsExpo, which was launched in June, 2014 at New York City's Javits Center as the largest 'Internet of Things' event in the world. The next @ThingsExpo will take place November 4-6, 2014, at the Santa Clara Convention Center, in Santa Clara, California. Since its launch in 2008, Cloud Expo TV commercials have been aired and CNBC, Fox News Network, and Bloomberg TV. Please enjoy our 2014 commercial.