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

Reusable (and Maintainable) Presentation Code

Helpful techniques

Everyone knows that you should reuse your code so that you don't have to repeatedly write the same functionality. You put widgets in custom tags and encapsulate logic in CFCs. Even so, your application's user interface may frequently end up changing. Sometimes the changes are so substantial that it hardly seems worth the effort to try to reuse code at all. Your efforts to reuse code and separate business logic from presentation aren't worthwhile unless you can write your presentation code so that it will be easy to change to fit changes to your clients' needs or other business requirement changes.

In this article, I will try to show a few techniques that I have found helpful in writing reusable code for application user interfaces. I'll use an example from a fictional search-reporting tool that was created in Dreamweaver and modified in HomeSite+.

Separate Logic and Presentation Code
If you look at Listing 1, the first thing that you might notice is that within the output loop I am querying the database for more information about each search term. This presents a number of problems, including the potential for very poor performance. The more pertinent problem, however, is that it clutters up the presentation code; making changes to this code is more confusing and tiresome (especially in cases where there is more logic code inside the output loop than is shown here).

The query logic (executed on each loop pass) can be pulled into the original query (see the SQL sidebar for more details). Pulling the logic into the original query improves performance (due to fewer connections to the database) and improves readability and maintainability of the code.

I would highly recommend that you learn and practice using some of the basic SQL aggregate functions such as GROUP BY and OUTER JOIN if you aren't already comfortable with them. The GROUP BY keyword is used in Listing 2 because it will return the results of aggregate functions across multiple rows by the columns in the GROUP BY statement.

All of this is standard SQL and therefore should work on most databases. Ben Forta's Teach Yourself SQL in 10 Minutes (Sams Publishing) covers this well, as does SQL for Dummies (Wiley Publishing). You may not want to learn from a Dummies book, but I first learned SQL from this book (after being introduced to it in Ben Forta's ColdFusion Web Application Construction Kit) and I think it is pretty good. Either book is a good choice - just remember that while the aforementioned CFWACK includes a good introduction to SQL, your life will be made easier by learning more.

Table 1 shows some standard aggregate functions. Since you are moving logic out of the output loop, look at this line:

<cfset PercentTotal = (numSearches / sumSearches) * 100>

This line also represents logic performed in the output loop. It is only one line so it probably isn't a major problem to leave it in the output loop. Even so, your life will be made easier in the long run if all of your logic is performed outside of the output. In this case, you can perform this calculation directly within the query itself - yes that's right, let the database do the work for you. (What if you couldn't? - see the Query Functions sidebar.)

As you can see from looking at Listing 2 (see sys-con.com/coldfusion/sourcec.cfm), the changes made the code much easier to read and, therefore, easier to maintain and modify.

Query Functions
In this case, the percent calculation was easy to perform in SQL. What if it weren't? Let's pretend that you couldn't perform that calculation in SQL. If that were the case, you would use the code in Listing 3 (see sys-con.com/coldfusion/sourcec.cfm).

As you can see, I created the column with a blank value in the SQL code itself. Immediately after the query, I looped through the results and set the value of that column to the result of the equation. This can be a very handy approach in situations where you have logic that cannot be performed in your SQL code but want to represent it within recordset rows.

Table 2 shows three built-in CFML query functions that I frequently find useful:

Separate Style from Output
Since the separation of logic from presentation is done, future listings won't include the logic portion of the code (as that won't be changing from previous listings).

Now the code is easier to read and maintain. The gray and teal color scheme fits in with the look of the (fictional) site for which this application is designed. However, it won't fit with the color scheme of every site on which you work (and may not work on the original site if and when it undergoes an eventual redesign).

You want to minimize the effort to import this application into another site and adopt that site's look and feel. If this were the only page of the application, it would be easy to change, but in all likelihood the application has more pages than this one. What can you do to make the transition easier?

Right now, all of the styling is intermixed with output code. If you want to change the look of anything, you have to go through every page of output and make the changes throughout all of the output code. To avoid such tedium, use CSS (cascading style sheets) to move the styling away from the display content itself.

Looking at Listing 4 (see sys-con.com/coldfusion/sourcec.cfm), you will see that CSS is used to set the styles outside of the output code (although not shown in the example, you could use an external style sheet - see the External Style Sheets sidebar). This centralizes a place to make changes (especially if multiple pages use the same styles) and eliminates the need for some extraneous HTML, thereby making the code easier to read and maintain. Another thing that I like about moving styles outside of output code is that it removes the need to escape your "#" in your color definitions - which used to be the cause of one of the most common errors that I would get during development. Sometimes you can also achieve display and layout traits that cannot be achieved without the use of CSS.

External Style Sheets
You can make your life easier and your load times faster if you move all of your styles to external style sheets. In order to do so, just move all of the code between the <style> tags (not including any HTML comments) into a new file and save it with a .css extension.

You have two major options for referencing your external style sheet from your page. Both options involve code that should be placed in the <head> section of your page.

<link rel="stylesheet" type="text/css" href="/all.css" />

This is the option that I use most frequently. It is widely supported even by older browsers and I find it easy to read.

<style type="text/css">@import url(/all.css);</style>

This option is also very good and widely supported by most (if not all) modern browsers. You can also use this same syntax (@import url(filename);) at the top of an external style sheet to import another style sheet.

This approach can be very handy for code reuse. Each application within a site can have its own style sheet. Each page of the site can import a site style sheet, which in turn imports style sheets for each application.

Using Descendant Selectors
My code still has a few remaining problems that aren't - perhaps - as easy to spot. One problem is that the background color of the row (not the cell) is set and not all browsers will apply that background color to each cell in the row like you want. Another is that if something else on the page is using one of the classes or tags that you are styling, it will affect those elements as well - with possibly unpleasant effects.

Fortunately, descendant selectors come to the rescue on both counts. Descendant selectors are not the same as the CSS cascade, rather they allow you to specify which elements to style based on how tags are nested within each other. As you can see in Listing 5 (see sys-con.com/coldfusion/sourcec.cfm), the table is surrounded with a div tag and id of searchapp. Then the styles are changed to take advantage of that change.

#searchapp th

This CSS means that the browser will apply the given styling to any th tag inside of any tag with an id of searchapp. Anything in this format will work the same way. Descendant selectors keep styles from being inadvertently applied where you don't want them. They also keep you from having to add lots of code to your page in order to apply styling correctly. In my opinion, descendant selectors are really what make CSS great.

#searchapp tr.odd td

As you can see, you can also nest your descendant selectors. This line applies the background color to any td tag below any tr tag that has a class of "odd." If you notice, a class of "even" is used as well, but apply styling isn't applied to it. This will leave it the default color. The nice thing about this approach is that you can easily style even rows later on if you want to do so.

Other Thoughts
When you are done with the modifications you can put all of your styles into one CSS file. I would recommend adding notes to that file to indicate styles that you have in your code, but are not explicitly styling in the CSS (so that you don't have to go searching through your code when you are ready to make a change). You could also use a variable for your mask for the DateFormat() function (and one for NumberFormat() and other formatting masks as well).

This approach has worked very well for me - I would love to hear how it works for you, as well as any ideas you might have. Hopefully, you will find this approach beneficial. Good luck!

More Stories By Steve Bryant

Steve Bryant is the founder and CEO of Bryant Web Consulting LLC (www.bryantwebconsulting.com) and teaches ColdFusion at Breakaway Interactive (www.breakawayinteractive.com). He got his BA in philosophy at Oklahoma State University. Steve, one of the top ColdFusion developers in the country, still has no idea how that led to a career in Web development. Steve blogs at steve.coldfusionjournal.com as one of CFDJ's published bloggers.

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
SYS-CON Events announced today that Dasher Technologies 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. Dasher Technologies, Inc. ® is a premier IT solution provider that delivers expert technical resources along with trusted account executives to architect and deliver complete IT solutions and services to help our clients execute their goals, plans and objectives. Since 1999, we'v...
SYS-CON Events announced today that TidalScale, a leading provider of systems and services, 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. TidalScale has been involved in shaping the computing landscape. They've designed, developed and deployed some of the most important and successful systems and services in the history of the computing industry - internet, Ethernet, operating s...
Enterprises have taken advantage of IoT to achieve important revenue and cost advantages. What is less apparent is how incumbent enterprises operating at scale have, following success with IoT, built analytic, operations management and software development capabilities – ranging from autonomous vehicles to manageable robotics installations. They have embraced these capabilities as if they were Silicon Valley startups. As a result, many firms employ new business models that place enormous impor...
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...
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...
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...
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.
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...
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.