Welcome!

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

Related Topics: ColdFusion

ColdFusion: Article

Expect The Unexpected

Expect The Unexpected

No one wants to write buggy code, at least no one I choose to know. Bugs are annoying, bugs are embarrassing. And bugs can cost you (and your clients) lots of time and money.

Bugfree code is the ideal all developers strive for - at least should strive for - but it's a lofty goal not easily attained.

To write bugfree code it's important to understand how bugs are introduced. I'd like to explore what I believe to be one of the primary causes for the introduction of bugs into your code: failure to expect the unexpected. While many of these ideas apply to application development in general, the positioning of this column relates specifically to ColdFusion.

Flow? What Flow?
Applications are designed with a particular program flow in mind. Users start at point A, go to point B, then to point C. Program flow is an important part of any application, and when developers write they anticipate a particular program flow.

Here are some examples.

  • A search dialog is displayed, the user enters search criteria, a search is performed and the results are displayed.

  • The user browses a product catalog, makes multiple selections with possible confirmations and provides payment information, after which the order is saved and processed.

  • A login screen is displayed and the user provides authentication information, which is validated against a database. If authenticated, access is granted; otherwise the login screen is redisplayed.

    In each of these examples there's a logical starting point, then a series of steps. The search dialog must be displayed before the search can be performed, users must select items from the product catalog before the order can be processed, and login information must be provided before access can be authenticated.

    In traditional application development, programmers had total control over program flow. Users had no way to access screens out of order, nor could they start from a screen other than the one they were supposed to start at. But Web applications, for better or worse, behave differently. As every Web page has a unique address (its URL), it's indeed possible for users to execute pages out of order, just as it's possible for them to start from the wrong page.

    How could this occur? There are several ways. Users could bookmark pages directly, search engines might index pages below your root, and newer browsers feature an auto-fill option that completes URLs for users but frequently uses the most recently visited page in the site (often the wrong page).

    To understand this better, look at the following code:

    <!--- Perform search --->
    <CFQUERY DATASOURCE="ds" NAME="search">
    SELECT title FROM books
    WHERE title LIKE %#FORM.title#%'
    </CFQUERY>
    <!--- Create page --->
    <HTML>
    <BODY>
    <H1>Search Results</H1>
    <UL>
    <!--- Display search results --->
    <CFOUTPUT QUERY="search">
    <LI>#title#
    </CFOUTPUT>
    </UL>
    </BODY>
    </HTML>

    What's wrong with the above code?

    Actually, this is fairly typical ColdFusion code (it's even commented). It performs a simple database search and displays the results. The search itself is driven by a form that contains a field named "title"

    And that's what's wrong. The code makes two dangerous assumptions - that the page will be called from a form and that the form contains a field named "title". If either assumption turns out to be incorrect, ColdFusion throws an error because #FORM.title# would refer to a variable that didn't exist.

    What's the solution? There are a couple of things you can and should do. The first is always check for the existence of variables before using them, initializing them with default values if needed. The ColdFusion <CFPARAM> tag is very useful for this, and good programming practices demand that every variable be initialized this way so they always exist (either as submitted FORM or URL values, or as locally created variables). If the following code were inserted above the code example, the page would always execute correctly, regardless of how it was invoked and what fields were passed:

    <CFPARAM NAME="FORM.title" DEFAULT="">

    Sometimes you may not want to use default values. For example, in the preceding code you may not want to display the entire contents of the table if the page is executed directly. If a user ends up on this page without having filled in the form to perform the search, you'd want to send them to the search page instead. Here's one way you could do this (assuming the search page was named search.cfm):

    <!--- Is form field present? --->
    <CFIF NOT IsDefined("FORM.title")>
    <!--- Not present, redirect to search screen --->
    <CFLOCATION URL="search.cfm">
    </CFIF>

    With this snippet at the top of the page your code is now safe. If users try to execute the page directly, you'll programmatically redirect them to where they really should be.

    The truth is, every page on your site should be written so that it's safe to execute directly. That way you'll never make assumptions about program flow, and your code won't break when the unexpected occurs.

    Are you up for a challenge? How about writing code that uses <CFDIRECTORY> to traverse your code tree to find all CFM pages, then looping through each one, executing it via <CFHTTP> to see which ones throw errors and which work. You could call this code daily (or weekly or monthly) and e-mail yourself the results so you'll know as soon as possible if things might break.

    Changes in Site Usage
    Another phenomenon that's part of Web site use is the frequency with which that use changes. Programmers anticipate that their site will be used in one way, but, inevitably, users find another way to use it. That's not a bad thing in and of itself, but it does present an interesting problem.

    All applications, not just Web-based applications, are designed so that particular parts perform better than others. This is usually because certain parts of the application are more critical and get more use, so the time and effort needed to improve and enhance the site tends to be best spent on these parts.

    The application hums along nicely, handling the load thrown at it, and everything works well until those pesky users start using your site in ways you didn't expect. Suddenly the efficient and highly optimized parts are being executed less and less, and the less fine-tuned (I'm being generous) parts start to buckle under the growing load.

    This is actually a very common problem. Some of the largest and most impressive sites on the Internet have fallen victim to it.

    The good news is that ColdFusion provides you with an invaluable (and frequently overlooked) tool you can use to identify these potential trouble spots. The ColdFusion Administrator (starting in version 4) features a checkbox that, when checked, allows you to log page requests that take longer than a specified amount of time.

    Again, the key here is to expect the unexpected and be ready when it occurs. Individual log entries aren't necessarily indicative of a problem, but repeated entries most definitely are. I'd strongly advise all site administrators to enable this option, even on production sites. Determine what the "normal" response time should be (and then pad that number a little) and have ColdFusion log all page requests that take longer. If specific pages start appearing in the log repeatedly, you'll know where to spend your fine-tuning and performance-enhancing efforts.

    Up for another challenge? Write a scheduled event that checks this log file daily for new entries. If it finds any, it should e-mail them to you so you'll know about them immediately.

    When Bad Things Happen
    You've cleaned up your site. You no longer expect specific program flow, nor do you expect specific usage patterns. That's great, but it's not enough.

    The other big trouble spot is reliance on other systems and technologies. Whether it's database integration, execution of third-party objects and components, or interaction with other Internet protocols (like HTTP, FTP and NNTP), the more you rely on other systems and technologies, the more room there is for something to go wrong.

    Whether it's database failure, the inability to connect to a specific host, or errors and problems in calls resources, they're all your problem because to the end user your site is broken. It's not an ideal world out there; bad things do happen and you'll be blamed. And you're not going to escape this one anytime soon.

    So what do you do? Again, ColdFusion (version 4 or later) provides a tool to respond to these situations - try catch error handling. While full coverage of try catch is beyond the scope of this column (I'll devote an entire column to error handling in the future), here's the basic idea.

    Try catch error handling allows you to trap errors in your code, then pick up the processing elsewhere when an error occurs. The basic page layout looks like this:

    <CFTRY>
    ... page goes here ...
    <CFCATCH>
    ... error processing goes here ...
    </CFCATCH>
    </CFTRY>

    By wrapping an entire page between <CFTRY> and </CFTRY> tags, any error that occurs within that page will be trapped. As soon as an error is caught, processing will be taken over by the catch block (the code between <CFCATCH> and </CFCATCH>). There's no limit to what you can place in the catch block-you can change variables, redirect requests, generate e-mail, write logs and even try to fix error conditions.

    Experienced developers take this one step further by nesting try catch error handling. Generic error handling is implemented at the page level, and additional error handling is implemented around specific features or functions. This type of implementation provides the greatest level of control and allows developers to not just expect the unexpected, but also to handle the unexpected.

    Conclusion
    The Internet is a highly dynamic and configurable environment. With all that flexibility and power comes the need for greater caution and planning to ensure that applications don't suddenly break. Bugfree code is a wonderful ideal, but for most of us, writing good code that doesn't break in unexpected scenarios is as close as we'll get to attaining it.

    The bottom line is that as developers writing code for this new environment, we must all expect the unexpected- because it's going to happen and usually at the least opportune time.

  • More Stories By Ben Forta

    Ben Forta is Adobe's Senior Technical Evangelist. In that capacity he spends a considerable amount of time talking and writing about Adobe products (with an emphasis on ColdFusion and Flex), and providing feedback to help shape the future direction of the products. By the way, if you are not yet a ColdFusion user, you should be. It is an incredible product, and is truly deserving of all the praise it has been receiving. In a prior life he was a ColdFusion customer (he wrote one of the first large high visibility web sites using the product) and was so impressed he ended up working for the company that created it (Allaire). Ben is also the author of books on ColdFusion, SQL, Windows 2000, JSP, WAP, Regular Expressions, and more. Before joining Adobe (well, Allaire actually, and then Macromedia and Allaire merged, and then Adobe bought Macromedia) he helped found a company called Car.com which provides automotive services (buy a car, sell a car, etc) over the Web. Car.com (including Stoneage) is one of the largest automotive web sites out there, was written entirely in ColdFusion, and is now owned by Auto-By-Tel.

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

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