Welcome!

ColdFusion Authors: Greg Ness, Liz McMillan, Pat Romanski, Andreas Grabner, David Strom

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.