|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.
Connected devices and the industrial internet are growing exponentially every year with Cisco expecting 50 billion devices to be in operation by 2020. In this period of growth, location-based insights are becoming invaluable to many businesses as they adopt new connected technologies. Knowing when and where these devices connect from is critical for a number of scenarios in supply chain management, disaster management, emergency response, M2M, location marketing and more. In his session at @Th...
Dec. 3, 2016 09:30 AM EST Reads: 3,918
"Dice has been around for the last 20 years. We have been helping tech professionals find new jobs and career opportunities," explained Manish Dixit, VP of Product and Engineering at Dice, in this SYS-CON.tv interview at 19th Cloud Expo, held November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA.
Dec. 3, 2016 09:30 AM EST Reads: 821
What happens when the different parts of a vehicle become smarter than the vehicle itself? As we move toward the era of smart everything, hundreds of entities in a vehicle that communicate with each other, the vehicle and external systems create a need for identity orchestration so that all entities work as a conglomerate. Much like an orchestra without a conductor, without the ability to secure, control, and connect the link between a vehicle’s head unit, devices, and systems and to manage the ...
Dec. 3, 2016 09:00 AM EST Reads: 443
"We're a cybersecurity firm that specializes in engineering security solutions both at the software and hardware level. Security cannot be an after-the-fact afterthought, which is what it's become," stated Richard Blech, Chief Executive Officer at Secure Channels, in this SYS-CON.tv interview at @ThingsExpo, held November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA.
Dec. 3, 2016 08:30 AM EST Reads: 483
In addition to all the benefits, IoT is also bringing new kind of customer experience challenges - cars that unlock themselves, thermostats turning houses into saunas and baby video monitors broadcasting over the internet. This list can only increase because while IoT services should be intuitive and simple to use, the delivery ecosystem is a myriad of potential problems as IoT explodes complexity. So finding a performance issue is like finding the proverbial needle in the haystack.
Dec. 3, 2016 06:30 AM EST Reads: 6,003
In his keynote at 18th Cloud Expo, Andrew Keys, Co-Founder of ConsenSys Enterprise, provided an overview of the evolution of the Internet and the Database and the future of their combination – the Blockchain. Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life sett...
Dec. 3, 2016 05:45 AM EST Reads: 6,920
The WebRTC Summit New York, to be held June 6-8, 2017, at the Javits Center in New York City, NY, announces that its Call for Papers is now open. Topics include all aspects of improving IT delivery by eliminating waste through automated business models leveraging cloud technologies. WebRTC Summit is co-located with 20th International Cloud Expo and @ThingsExpo. WebRTC is the future of browser-to-browser communications, and continues to make inroads into the traditional, difficult, plug-in web ...
Dec. 3, 2016 05:30 AM EST Reads: 1,200
20th Cloud Expo, taking place June 6-8, 2017, at the Javits Center in New York City, NY, will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud strategy.
Dec. 3, 2016 04:15 AM EST Reads: 1,718
Internet-of-Things discussions can end up either going down the consumer gadget rabbit hole or focused on the sort of data logging that industrial manufacturers have been doing forever. However, in fact, companies today are already using IoT data both to optimize their operational technology and to improve the experience of customer interactions in novel ways. In his session at @ThingsExpo, Gordon Haff, Red Hat Technology Evangelist, will share examples from a wide range of industries – includin...
Dec. 3, 2016 02:30 AM EST Reads: 1,523
WebRTC is the future of browser-to-browser communications, and continues to make inroads into the traditional, difficult, plug-in web communications world. The 6th WebRTC Summit continues our tradition of delivering the latest and greatest presentations within the world of WebRTC. Topics include voice calling, video chat, P2P file sharing, and use cases that have already leveraged the power and convenience of WebRTC.
Dec. 3, 2016 02:15 AM EST Reads: 1,501
"We build IoT infrastructure products - when you have to integrate different devices, different systems and cloud you have to build an application to do that but we eliminate the need to build an application. Our products can integrate any device, any system, any cloud regardless of protocol," explained Peter Jung, Chief Product Officer at Pulzze Systems, in this SYS-CON.tv interview at @ThingsExpo, held November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA.
Dec. 3, 2016 01:45 AM EST Reads: 788
Data is the fuel that drives the machine learning algorithmic engines and ultimately provides the business value. In his session at 20th Cloud Expo, Ed Featherston, director/senior enterprise architect at Collaborative Consulting, will discuss the key considerations around quality, volume, timeliness, and pedigree that must be dealt with in order to properly fuel that engine.
Dec. 3, 2016 12:30 AM EST Reads: 1,524
"Once customers get a year into their IoT deployments, they start to realize that they may have been shortsighted in the ways they built out their deployment and the key thing I see a lot of people looking at is - how can I take equipment data, pull it back in an IoT solution and show it in a dashboard," stated Dave McCarthy, Director of Products at Bsquare Corporation, in this SYS-CON.tv interview at @ThingsExpo, held November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA.
Dec. 2, 2016 11:15 PM EST Reads: 916
IoT is rapidly changing the way enterprises are using data to improve business decision-making. In order to derive business value, organizations must unlock insights from the data gathered and then act on these. In their session at @ThingsExpo, Eric Hoffman, Vice President at EastBanc Technologies, and Peter Shashkin, Head of Development Department at EastBanc Technologies, discussed how one organization leveraged IoT, cloud technology and data analysis to improve customer experiences and effici...
Dec. 2, 2016 08:30 PM EST Reads: 4,984
Fact is, enterprises have significant legacy voice infrastructure that’s costly to replace with pure IP solutions. How can we bring this analog infrastructure into our shiny new cloud applications? There are proven methods to bind both legacy voice applications and traditional PSTN audio into cloud-based applications and services at a carrier scale. Some of the most successful implementations leverage WebRTC, WebSockets, SIP and other open source technologies. In his session at @ThingsExpo, Da...
Dec. 2, 2016 08:15 PM EST Reads: 1,574
"IoT is going to be a huge industry with a lot of value for end users, for industries, for consumers, for manufacturers. How can we use cloud to effectively manage IoT applications," stated Ian Khan, Innovation & Marketing Manager at Solgeniakhela, in this SYS-CON.tv interview at @ThingsExpo, held November 3-5, 2015, at the Santa Clara Convention Center in Santa Clara, CA.
Dec. 2, 2016 06:45 PM EST Reads: 4,001
As data explodes in quantity, importance and from new sources, the need for managing and protecting data residing across physical, virtual, and cloud environments grow with it. Managing data includes protecting it, indexing and classifying it for true, long-term management, compliance and E-Discovery. Commvault can ensure this with a single pane of glass solution – whether in a private cloud, a Service Provider delivered public cloud or a hybrid cloud environment – across the heterogeneous enter...
Dec. 2, 2016 06:30 PM EST Reads: 1,489
The cloud promises new levels of agility and cost-savings for Big Data, data warehousing and analytics. But it’s challenging to understand all the options – from IaaS and PaaS to newer services like HaaS (Hadoop as a Service) and BDaaS (Big Data as a Service). In her session at @BigDataExpo at @ThingsExpo, Hannah Smalltree, a director at Cazena, provided an educational overview of emerging “as-a-service” options for Big Data in the cloud. This is critical background for IT and data professionals...
Dec. 2, 2016 05:00 PM EST Reads: 4,089
Today we can collect lots and lots of performance data. We build beautiful dashboards and even have fancy query languages to access and transform the data. Still performance data is a secret language only a couple of people understand. The more business becomes digital the more stakeholders are interested in this data including how it relates to business. Some of these people have never used a monitoring tool before. They have a question on their mind like “How is my application doing” but no id...
Dec. 2, 2016 04:45 PM EST Reads: 2,119
@GonzalezCarmen has been ranked the Number One Influencer and @ThingsExpo has been named the Number One Brand in the “M2M 2016: Top 100 Influencers and Brands” by Onalytica. Onalytica analyzed tweets over the last 6 months mentioning the keywords M2M OR “Machine to Machine.” They then identified the top 100 most influential brands and individuals leading the discussion on Twitter.
Dec. 2, 2016 04:45 PM EST Reads: 1,985