Welcome!

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.

SQL
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
When growing capacity and power in the data center, the architectural trade-offs between server scale-up vs. scale-out continue to be debated. Both approaches are valid: scale-out adds multiple, smaller servers running in a distributed computing model, while scale-up adds fewer, more powerful servers that are capable of running larger workloads. It’s worth noting that there are additional, unique advantages that scale-up architectures offer. One big advantage is large memory and compute capacity...
Artificial intelligence, machine learning, neural networks. We’re in the midst of a wave of excitement around AI such as hasn’t been seen for a few decades. But those previous periods of inflated expectations led to troughs of disappointment. Will this time be different? Most likely. Applications of AI such as predictive analytics are already decreasing costs and improving reliability of industrial machinery. Furthermore, the funding and research going into AI now comes from a wide range of com...
No hype cycles or predictions of zillions of things here. IoT is big. You get it. You know your business and have great ideas for a business transformation strategy. What comes next? Time to make it happen. In his session at @ThingsExpo, Jay Mason, Associate Partner at M&S Consulting, presented a step-by-step plan to develop your technology implementation strategy. He discussed the evaluation of communication standards and IoT messaging protocols, data analytics considerations, edge-to-cloud tec...
"When we talk about cloud without compromise what we're talking about is that when people think about 'I need the flexibility of the cloud' - it's the ability to create applications and run them in a cloud environment that's far more flexible,” explained Matthew Finnie, CTO of Interoute, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
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
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.
In his session at @ThingsExpo, Eric Lachapelle, CEO of the Professional Evaluation and Certification Board (PECB), provided an overview of various initiatives to certify the security of connected devices and future trends in ensuring public trust of IoT. Eric Lachapelle is the Chief Executive Officer of the Professional Evaluation and Certification Board (PECB), an international certification body. His role is to help companies and individuals to achieve professional, accredited and worldwide re...
The Internet giants are fully embracing AI. All the services they offer to their customers are aimed at drawing a map of the world with the data they get. The AIs from these companies are used to build disruptive approaches that cannot be used by established enterprises, which are threatened by these disruptions. However, most leaders underestimate the effect this will have on their businesses. In his session at 21st Cloud Expo, Rene Buest, Director Market Research & Technology Evangelism at Ara...
SYS-CON Events announced today that Enzu will exhibit at SYS-CON's 21st Int\ernational Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Enzu’s mission is to be the leading provider of enterprise cloud solutions worldwide. Enzu enables online businesses to use its IT infrastructure to their competitive advantage. By offering a suite of proven hosting and management services, Enzu wants companies to focus on the core of their ...
Internet of @ThingsExpo, taking place October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with 21st Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. 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 devic...
Amazon started as an online bookseller 20 years ago. Since then, it has evolved into a technology juggernaut that has disrupted multiple markets and industries and touches many aspects of our lives. It is a relentless technology and business model innovator driving disruption throughout numerous ecosystems. Amazon’s AWS revenues alone are approaching $16B a year making it one of the largest IT companies in the world. With dominant offerings in Cloud, IoT, eCommerce, Big Data, AI, Digital Assista...
SYS-CON Events announced today that Cloud Academy named "Bronze Sponsor" of 21st International Cloud Expo which will take place October 31 - November 2, 2017 at the Santa Clara Convention Center in Santa Clara, CA. Cloud Academy is the industry’s most innovative, vendor-neutral cloud technology training platform. Cloud Academy provides continuous learning solutions for individuals and enterprise teams for Amazon Web Services, Microsoft Azure, Google Cloud Platform, and the most popular cloud com...
SYS-CON Events announced today that MobiDev, a client-oriented software development company, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. MobiDev is a software company that develops and delivers turn-key mobile apps, websites, web services, and complex software systems for startups and enterprises. Since 2009 it has grown from a small group of passionate engineers and business...
SYS-CON Events announced today that GrapeUp, the leading provider of rapid product development at the speed of business, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Grape Up is a software company, specialized in cloud native application development and professional services related to Cloud Foundry PaaS. With five expert teams that operate in various sectors of the market acr...
SYS-CON Events announced today that Ayehu will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on October 31 - November 2, 2017 at the Santa Clara Convention Center in Santa Clara California. Ayehu provides IT Process Automation & Orchestration solutions for IT and Security professionals to identify and resolve critical incidents and enable rapid containment, eradication, and recovery from cyber security breaches. Ayehu provides customers greater control over IT infras...
With the introduction of IoT and Smart Living in every aspect of our lives, one question has become relevant: What are the security implications? To answer this, first we have to look and explore the security models of the technologies that IoT is founded upon. In his session at @ThingsExpo, Nevi Kaja, a Research Engineer at Ford Motor Company, discussed some of the security challenges of the IoT infrastructure and related how these aspects impact Smart Living. The material was delivered interac...
In his session at Cloud Expo, Alan Winters, an entertainment executive/TV producer turned serial entrepreneur, presented a success story of an entrepreneur who has both suffered through and benefited from offshore development across multiple businesses: The smart choice, or how to select the right offshore development partner Warning signs, or how to minimize chances of making the wrong choice Collaboration, or how to establish the most effective work processes Budget control, or how to ma...
IoT solutions exploit operational data generated by Internet-connected smart “things” for the purpose of gaining operational insight and producing “better outcomes” (for example, create new business models, eliminate unscheduled maintenance, etc.). The explosive proliferation of IoT solutions will result in an exponential growth in the volume of IoT data, precipitating significant Information Governance issues: who owns the IoT data, what are the rights/duties of IoT solutions adopters towards t...
SYS-CON Events announced today that CA Technologies has been named "Platinum Sponsor" of SYS-CON's 21st International Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. CA Technologies helps customers succeed in a future where every business - from apparel to energy - is being rewritten by software. From planning to development to management to security, CA creates software that fuels transformation for companies in the applic...
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.