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
DXWordEXPO New York 2018, colocated with CloudEXPO New York 2018 will be held November 11-13, 2018, in New York City and will bring together Cloud Computing, FinTech and Blockchain, Digital Transformation, Big Data, Internet of Things, DevOps, AI, Machine Learning and WebRTC to one location.
DXWorldEXPO | CloudEXPO are the world's most influential, independent events where Cloud Computing was coined and where technology buyers and vendors meet to experience and discuss the big picture of Digital Transformation and all of the strategies, tactics, and tools they need to realize their goals. Sponsors of DXWorldEXPO | CloudEXPO benefit from unmatched branding, profile building and lead generation opportunities.
DXWorldEXPO LLC announced today that ICOHOLDER named "Media Sponsor" of Miami Blockchain Event by FinTechEXPO. ICOHOLDER give you detailed information and help the community to invest in the trusty projects. Miami Blockchain Event by FinTechEXPO has opened its Call for Papers. The two-day event will present 20 top Blockchain experts. All speaking inquiries which covers the following information can be submitted by email to [email protected] Miami Blockchain Event by FinTechEXPO also offers s...
Dion Hinchcliffe is an internationally recognized digital expert, bestselling book author, frequent keynote speaker, analyst, futurist, and transformation expert based in Washington, DC. He is currently Chief Strategy Officer at the industry-leading digital strategy and online community solutions firm, 7Summits.
Digital Transformation and Disruption, Amazon Style - What You Can Learn. Chris Kocher is a co-founder of Grey Heron, a management and strategic marketing consulting firm. He has 25+ years in both strategic and hands-on operating experience helping executives and investors build revenues and shareholder value. He has consulted with over 130 companies on innovating with new business models, product strategies and monetization. Chris has held management positions at HP and Symantec in addition to ...
Cloud-enabled transformation has evolved from cost saving measure to business innovation strategy -- one that combines the cloud with cognitive capabilities to drive market disruption. Learn how you can achieve the insight and agility you need to gain a competitive advantage. Industry-acclaimed CTO and cloud expert, Shankar Kalyana presents. Only the most exceptional IBMers are appointed with the rare distinction of IBM Fellow, the highest technical honor in the company. Shankar has also receive...
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.
The standardization of container runtimes and images has sparked the creation of an almost overwhelming number of new open source projects that build on and otherwise work with these specifications. Of course, there's Kubernetes, which orchestrates and manages collections of containers. It was one of the first and best-known examples of projects that make containers truly useful for production use. However, more recently, the container ecosystem has truly exploded. A service mesh like Istio addr...
Poor data quality and analytics drive down business value. In fact, Gartner estimated that the average financial impact of poor data quality on organizations is $9.7 million per year. But bad data is much more than a cost center. By eroding trust in information, analytics and the business decisions based on these, it is a serious impediment to digital transformation.
Predicting the future has never been more challenging - not because of the lack of data but because of the flood of ungoverned and risk laden information. Microsoft states that 2.5 exabytes of data are created every day. Expectations and reliance on data are being pushed to the limits, as demands around hybrid options continue to grow.
Business professionals no longer wonder if they'll migrate to the cloud; it's now a matter of when. The cloud environment has proved to be a major force in transitioning to an agile business model that enables quick decisions and fast implementation that solidify customer relationships. And when the cloud is combined with the power of cognitive computing, it drives innovation and transformation that achieves astounding competitive advantage.
As IoT continues to increase momentum, so does the associated risk. Secure Device Lifecycle Management (DLM) is ranked as one of the most important technology areas of IoT. Driving this trend is the realization that secure support for IoT devices provides companies the ability to deliver high-quality, reliable, secure offerings faster, create new revenue streams, and reduce support costs, all while building a competitive advantage in their markets. In this session, we will use customer use cases...
Digital Transformation: Preparing Cloud & IoT Security for the Age of Artificial Intelligence. As automation and artificial intelligence (AI) power solution development and delivery, many businesses need to build backend cloud capabilities. Well-poised organizations, marketing smart devices with AI and BlockChain capabilities prepare to refine compliance and regulatory capabilities in 2018. Volumes of health, financial, technical and privacy data, along with tightening compliance requirements by...
The IoT Will Grow: In what might be the most obvious prediction of the decade, the IoT will continue to expand next year, with more and more devices coming online every single day. What isn’t so obvious about this prediction: where that growth will occur. The retail, healthcare, and industrial/supply chain industries will likely see the greatest growth. Forrester Research has predicted the IoT will become “the backbone” of customer value as it continues to grow. It is no surprise that retail is ...
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 settlement products to hedge funds and investment banks. After, he co-founded a revenue cycle management company where he learned about Bitcoin and eventually Ethereal. Andrew's role at ConsenSys Enterprise is a mul...
The best way to leverage your Cloud Expo presence as a sponsor and exhibitor is to plan your news announcements around our events. The press covering Cloud Expo and @ThingsExpo will have access to these releases and will amplify your news announcements. More than two dozen Cloud companies either set deals at our shows or have announced their mergers and acquisitions at Cloud Expo. Product announcements during our show provide your company with the most reach through our targeted audiences.
DevOpsSummit New York 2018, colocated with CloudEXPO | DXWorldEXPO New York 2018 will be held November 11-13, 2018, in New York City. Digital Transformation (DX) is a major focus with the introduction of DXWorldEXPO within the program. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of bus...
With 10 simultaneous tracks, keynotes, general sessions and targeted breakout classes, @CloudEXPO and DXWorldEXPO are two of the most important technology events of the year. Since its launch over eight years ago, @CloudEXPO and DXWorldEXPO have presented a rock star faculty as well as showcased hundreds of sponsors and exhibitors! In this blog post, we provide 7 tips on how, as part of our world-class faculty, you can deliver one of the most popular sessions at our events. But before reading...
DXWorldEXPO LLC announced today that "Miami Blockchain Event by FinTechEXPO" has announced that its Call for Papers is now open. The two-day event will present 20 top Blockchain experts. All speaking inquiries which covers the following information can be submitted by email to [email protected] Financial enterprises in New York City, London, Singapore, and other world financial capitals are embracing a new generation of smart, automated FinTech that eliminates many cumbersome, slow, and expe...
Cloud Expo | DXWorld Expo have announced the conference tracks for Cloud Expo 2018. Cloud Expo will be held June 5-7, 2018, at the Javits Center in New York City, and November 6-8, 2018, at the Santa Clara Convention Center, Santa Clara, CA. Digital Transformation (DX) is a major focus with the introduction of DX Expo within the program. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive ov...