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

Design Patterns in ColdFusion: Template Method Pattern

Design Patterns in ColdFusion: Template Method Pattern

ColdFusion has always been an interesting Rapid Application Development tool but never a language taken completely seriously by object-oriented programmers because of its purely structural nature. C++ and Java CFX tags, and the somewhat unreliable nature of <cfobject>, kept many advanced programming concepts unreachable by the average CF5 developer. With the release of ColdFusion MX, Macromedia simplified the use of Java from within ColdFusion. Additionally, the language itself has been extended to include a Java class-like construct known as ColdFusion Components (CFCs). With this new construct and a more object-oriented syntax comes an inevitable learning curve as we throw aside (some) of our old structured programming techniques and adapt others to a newer and ultimately better way of doing things. Hopefully you've already been experimenting with CFCs and are looking for ways to organize and reuse your code. If so, design patterns may be just what you are looking for.

Enter Design Patterns
When ColdFusion developers think of design patterns we tend to think of graphical user interface (GUI) patterns, which may relate to navigation or a user's experience or path through a specific site or application. Two common examples are Bread Crumbs, in which a path of links is displayed to traverse back up through a site's hierarchy; and Double Tab, in which a top level of links reveals a different sub-level of links underneath. However, these are not what most developers think of when they think of design patterns.

When Java or C++ developers think of design patterns they tend to think of language-neutral patterns they apply to solve common programming problems. These common problems have already been encountered and solved countless times in the past. As developers we need only to be able to recognize these common problems and implement the appropriate solution. Think of them as tried-and-true answers to age-old questions.

Many of these answers and questions were compiled into a book by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides - commonly referred to as the "Gang of Four." Their book, Design Patterns: Elements of reusable object-oriented software, is the premier book on design patterns in software development. Interfaces for many of the patterns discussed in their book were specifically written into the Java foundation classes, which form the core of the Java programming language. Although the examples in the book are written in C++ and Smalltalk, the concepts presented remain the same. Some of these patterns may not be feasible or desirable due to the stateless and performance-driven nature of Web programming. Many other patterns are just as useful to ColdFusion developers as they are to our friends in C++. One of these is the Template Method pattern.

What Is the Template Method Pattern?
The Gang of Four book describes the Template Method pattern as "defining the skeleton of an algorithm in an operation, deferring some steps to subclasses, while letting subclasses redefine certain steps of an algorithm without changing the algorithm's structure."

OK, so what does that mean? It means that the Template Method pattern is firmly rooted in the principles of two major OOP concepts: inheritance and polymorphism.

Inheritance in ColdFusion involves a top-level CFC that contains common functionality and is known as a "base class" or base CFC. Any CFC that extends a base CFC is seen as deriving from or extending that CFC. A derived CFC "inherits" all of the base CFC's methods and data members. The relationship between a derived CFC and its base CFC is known as an "is a" relationship. The derived CFC "is a" base CFC. If we have a derived CFC called "Employee" that extends the User base CFC, then we would say that Employee "is a" User.

Polymorphism, or more specifically subtype polymorphism, is the ability to override and redefine methods in "derived" CFCs that they inherit from their "base class" CFC. Because of the relationship they have with a common base CFC, all related CFCs can be treated similarly and we can guarantee some level of compatibility with common methods. No matter what derived CFC we're working with, we know generally that an inherited or overridden method will work the right way for the actual CFC being processed. These methods will be processed differently depending on whether the actual method being executed at runtime is implemented in the base CFC or a derived CFC. Take the Employee and User CFCs shown. If User has an Authenticate() method, we know that through inheritance that Employee will have one as well. Although Employee may override the version of the method it inherits from User, we can assume that their arguments and what they return will act similarly, making them interchangeable in some circumstances. This interchangeability is what defines them as polymorphic (see Figure 1).

The Template Method pattern is one of the most important concepts for those unfamiliar with OOP and design patterns because it relies so heavily on, and encourages the use of, inheritance and polymorphism. These fundamental object-oriented principles form the foundation of many design patterns.

Template Method Pattern Explained
The Template Method pattern requires at least two derived CFCs and a base class CFC, which may be abstract. In OOP, an abstract base class is one that defines the behavior of any classes that extend it while deferring some of the actual implementation to those derived classes. In other words, the base class CFC is abstract because it defines the names and function calls for certain methods that it does not itself implement. Abstract CFCs or methods are not an inherently available feature in ColdFusion as there is no place to define them as being abstract. However, implementing them is still relatively easy. For abstract methods in CFCs I use a <cfabort> tag with a custom error message to ensure the method implementation from the base class CFC is not called.

<cffunction name="DoSomething" access="public" output="false" returntype="string">
<!--- Abstract Method - Must be overridden or will abort --->
<cfabort showerror="This Method is Abstract and needs to be overridden">
</cffunction>

A Template method is a method in the base CFC. A Template method is concrete, meaning it is implemented in the base CFC, and calls one or more Hook methods. A Hook method is a method in a CFC that defines a task that will be overridden in any CFC that derives from it. "Hook" refers to a place to hang your customizable code. Hook methods are usually abstract but can have a default implementation in the base CFC. It also must be ensured that all Hook methods behave uniformly to enforce polymorphism. Any CFC that derives from this base CFC is referred to as concrete if it overrides all inherited abstract methods. These concrete derived CFCs provide the implementation of the Hook methods (see Figure 2).

The Template Method pattern is most useful when you have two or more different components (custom tags, CFCs) that duplicate a significant portion of each other's code yet do not reuse or share any portion of this code through custom tags, CFIncludes, or CFCs. If a change that affects these components becomes necessary, changes must be made to all the relevant members individually.

To alleviate this problem a developer may decide to break out the steps of the algorithm so the duplicate code can be shared and the variable code can be implemented independently. The shared steps are implemented as concrete method(s) in the base CFC, while the unique steps are given either an abstract or a default implementation as method(s) in the base CFC. These unique steps represent "hooks" that will need to be implemented as concrete methods in any derived CFC. This is a somewhat unusual concept as the method being called is in the base CFC and it in turn is calling Hook methods in whatever derived CFC has been instantiated. The Gang of Four refers to this somewhat inverted top-down control structure as "the Hollywood principle" - "Don't call us, we'll call you."

Why the Template Method Pattern?
One major advantage to the type of polymorphic behavior exhibited in the Template Method pattern is that it generally removes the "switch" constructs required in purely structured languages like previous versions of ColdFusion. As CF5 developers we often try to repurpose custom tags to fit more than one type of situation. In doing so we often need to pass in a type attribute that describes what structure or data type the custom tag is performing the action on or possibly what type of action to perform. Here is an example custom tag call for processing a credit card transaction:

<cf_processCreditCard type="#form.CCtype#"
CCnumber="#form.ccnumber#"
Expiration="#form.Expiration #"
Amount="#form.Amount #"
SecurityCode="#form.SecurityCode #"
Name="#form.Name#"
Street1="#form.Street1#"
Street2="#form.Street2#"
City="#form.City #"
State="#form.State #"
Zip="#form.Zip #" />

This is then followed by a <cfswitch> or <cfif>, which separates the actual processing.

<cfswitch expression="#attributes.type#">
<cfcase value="Visa">
<!--- Verify Credit Card Address - - - >
<!--- Process CC Transaction - - - >

...etc ...
</cfcase>
<cfcase value="Amex">
<!--- Verify Credit Card Address - - - >
<!--- Process CC Transaction - - - >

...etc ...
</cfcase>
...etc ...
</cfswitch>

Now the code that executes to "Verify Credit Card Address" may be the same for Visa and MasterCard, but we can't reuse it without another layer of <cfswitch> and <cfif> inside our existing <cfswitch>. However, by using inheritance and polymorphism, and the Template Method pattern of course, we can deal with this in a more architecturally elegant way.

The Template Method Pattern in Action
We know that to implement the ProcessCreditCard custom tag as CFCs using the Template Method pattern we need a base class for our Credit Card CFCs. We also know this base CFC needs two Hook methods; VerifyAddress() and ProcessCCTrans(). These will be abstract in our base CFC but will need to be implemented in any derived CFCs. Next we need to implement a Template method in our base CFC called RunTransaction(). RunTransaction() calls the two Hook methods VerifyAddress() and ProcessCCTrans() (see Listing 1).

Now we need our derived CFCs for Visa and Amex, which will have independent implementations of the VerifyAddress() and ProcessCCTrans(). These Hook methods from our base CFC must be concrete in our derived CFCs (see Listings 2 and 3).

Both derived CFCs contain implementations of the VerifyAddress() and ProcessCCTrans() methods. The AddressData argument is a structure that is passed through to the VerifyAddress() method implementations. The TransactionData structure is the equivalent for the ProcessCCTrans() method. Both implementations of these methods take one argument, a structure, which allows us to vary the number and name of arguments for each method depending upon their derived implementation (see Figure 3). The Template Method RunTransaction() is fairly simple:

<cffunction name="RunTransaction" access="public" output="false" returntype="string">
<cfargument name="addressData" required="true" type="struct">
<cfargument name="transactionData" required="true" type="struct">
<cfif VerifyAddress(arguments.addressData)>
<cfreturn processCCTrans(arguments.transactionData)>
<cfelse>
<cfreturn "Cannot Verify Address">
</cfif>
</cffunction>

If the derived method implementation of VerifyAddress() being called returns false then we return the string "Cannot Verify Address" to the calling page. If it returns true (the address has been verified) we can proceed to processing the transaction. We simply return whatever is returned by the derived implementation of processCCTrans() to the caller.

On the calling page for our Template method example we are processing the submit form for a e-commerce application (see Listing 4).

First we need to instantiate a CFC for the type of credit card being processed. We create the data structures to pass in to the runTransaction() method that will be passed through to the verifyAddress() and ProcessCCTrans() methods. If a security code has been passed in via the form then add it to the transactionData structure to be passed through to the ProcessCCTrans() method. This would only apply if we had an instance of a VisaCC.cfc because American Express cards do not have security codes. We then invoke the RunTransaction() method passing in the two structures. Regardless of which credit card is being processed the algorithm remains constant while the actual implementation of pieces of said algorithm can vary.

Factoring
The Template Method pattern also relies heavily on a software concept called factoring. Factoring is simply identifying duplicate behavior in related CFCs and moving it up into the base CFC. Because they are often written at different times, the code in related CFCs may not be duplicated exactly but the behavior may be. After you have separated the behavior that is duplicated from that which is not, you can move the duplicated behavior up into the base CFC while leaving the unique behavior in the derived CFCs. Refactoring is the process of going back to your derived CFCs every so often and factoring the common behavior up into the base CFC.

Conclusion
As we ColdFusion developers reuse, or more often repurpose, code in custom tags, we often end up solving a very specific problem with a very specific solution. While the <cf_ProcessCreditCard> custom tag does provide some code reuse, it is hardly the best or most future-proof answer to the problem. With the advent of CFCs and some knowledge of object-oriented design patterns we can learn to recognize common issues or patterns that come up often in software development and implement tried and tested solutions.

More Stories By Brendan O'Hara

Brendan O'Hara is a software architect and CEO of Exos Technology LLC, a software consulting firm in the Philadelphia suburbs.
He co-authored the Advanced Macromedia ColdFusion MX Application Development, published by Macromedia Press, and was
technical reviewer for Programming ColdFusion MX by O'Reilly. Brendan is a Team Macromedia volunteer for
ColdFusion and chairman and founder of the Philadelphia Developers Network. [email protected]

Comments (5) View Comments

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.


Most Recent Comments
SandRat_44 08/12/03 10:38:57 AM EDT

I was first an OO programmer (C++) then an network admin, now a CF programmer. Been using CFC's (hurray!!! at last something OO!!!) to model the problems I've coded for, but this article sheds light on the work I've been doing. I wasn't nuts after all!

I feel sorry for the glazed over eyes of our young interns that just don't get it. What are they teaching in college these days? Many come from reputable colleges but only seem to have technical skills and not the foundational knowledge (like the concept of Objects). I have bookmarked and sent them this article. Good Job, to you and Hal Helms (I was reading his article in Vol 5 - issue 6 that pointed here.)

Chris Peters 06/12/03 01:33:00 PM EDT

I reminisced back to when I was sitting in my college Java course.

This is useful knowledge. I recommend bookmarking this article, coming back to it, and rereading it until you know it like the back of your hand.

RB 05/11/03 12:10:00 AM EDT

It clearly explained the GoF template method design pattern using cold fusion concepts.

CFC's are a great addition to CFMX, but in order to use them properly, you really need to know design patterns. That can be hard for a cf developer because learning design patterns usually means having to learn an oo language first. Now that we have cfc's, we need more articles like this one.

Keep up the good work!

Joe Schmoe 03/19/03 02:04:00 PM EST

mee too

venkat bathula 03/08/03 04:05:00 PM EST

i am interested in coldfusion

@ThingsExpo Stories
"We've been engaging with a lot of customers including Panasonic, we've been involved with Cisco and now we're working with the U.S. government - the Department of Homeland Security," explained Peter Jung, Chief Product Officer at Pulzze Systems, in this SYS-CON.tv interview at @ThingsExpo, held June 6-8, 2017, at the Javits Center in New York City, NY.
"We provide IoT solutions. We provide the most compatible solutions for many applications. Our solutions are industry agnostic and also protocol agnostic," explained Richard Han, Head of Sales and Marketing and Engineering at Systena America, in this SYS-CON.tv interview at @ThingsExpo, held June 6-8, 2017, at the Javits Center in New York City, NY.
SYS-CON Events announced today that Calligo, an innovative cloud service provider offering mid-sized companies the highest levels of data privacy and security, 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. Calligo offers unparalleled application performance guarantees, commercial flexibility and a personalised support service from its globally located cloud plat...
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...
"The Striim platform is a full end-to-end streaming integration and analytics platform that is middleware that covers a lot of different use cases," explained Steve Wilkes, Founder and CTO at Striim, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
SYS-CON Events announced today that DXWorldExpo has been named “Global 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. Digital Transformation is the key issue driving the global enterprise IT business. Digital Transformation is most prominent among Global 2000 enterprises and government institutions.
SYS-CON Events announced today that Datera, that offers a radically new data management architecture, has been named "Exhibitor" 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. Datera is transforming the traditional datacenter model through modern cloud simplicity. The technology industry is at another major inflection point. The rise of mobile, the Internet of Things, data storage and Big...
"We are focused on SAP running in the clouds, to make this super easy because we believe in the tremendous value of those powerful worlds - SAP and the cloud," explained Frank Stienhans, CTO of Ocean9, Inc., in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
DX World EXPO, LLC., a Lighthouse Point, Florida-based startup trade show producer and the creator of "DXWorldEXPO® - Digital Transformation Conference & Expo" has announced its executive management team. The team is headed by Levent Selamoglu, who has been named CEO. "Now is the time for a truly global DX event, to bring together the leading minds from the technology world in a conversation about Digital Transformation," he said in making the announcement.
"MobiDev is a Ukraine-based software development company. We do mobile development, and we're specialists in that. But we do full stack software development for entrepreneurs, for emerging companies, and for enterprise ventures," explained Alan Winters, U.S. Head of Business Development at MobiDev, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
While the focus and objectives of IoT initiatives are many and diverse, they all share a few common attributes, and one of those is the network. Commonly, that network includes the Internet, over which there isn't any real control for performance and availability. Or is there? The current state of the art for Big Data analytics, as applied to network telemetry, offers new opportunities for improving and assuring operational integrity. In his session at @ThingsExpo, Jim Frey, Vice President of S...
SYS-CON Events announced today that DXWorldExpo has been named “Global 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. Digital Transformation is the key issue driving the global enterprise IT business. Digital Transformation is most prominent among Global 2000 enterprises and government institutions.
In his opening keynote at 20th Cloud Expo, Michael Maximilien, Research Scientist, Architect, and Engineer at IBM, discussed the full potential of the cloud and social data requires artificial intelligence. By mixing Cloud Foundry and the rich set of Watson services, IBM's Bluemix is the best cloud operating system for enterprises today, providing rapid development and deployment of applications that can take advantage of the rich catalog of Watson services to help drive insights from the vast t...
SYS-CON Events announced today that EnterpriseTech has been named “Media 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. EnterpriseTech is a professional resource for news and intelligence covering the migration of high-end technologies into the enterprise and business-IT industry, with a special focus on high-tech solutions in new product development, workload management, increased effic...
SYS-CON Events announced today that Massive Networks, that helps your business operate seamlessly with fast, reliable, and secure internet and network solutions, has been named "Exhibitor" 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. As a premier telecommunications provider, Massive Networks is headquartered out of Louisville, Colorado. With years of experience under their belt, their team of...
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 Cloudistics, an on-premises cloud computing company, 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. Cloudistics delivers a complete public cloud experience with composable on-premises infrastructures to medium and large enterprises. Its software-defined technology natively converges network, storage, compute, virtualization, and ...
SYS-CON Events announced today that CHEETAH Training & Innovation 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. CHEETAH Training & Innovation is a cloud consulting and IT training firm specializing in improving clients cloud strategies and infrastructures for medium to large companies.
SYS-CON Events announced today that Datanami has been named “Media 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. Datanami is a communication channel dedicated to providing insight, analysis and up-to-the-minute information about emerging trends and solutions in Big Data. The publication sheds light on all cutting-edge technologies including networking, storage and applications, and thei...
The current age of digital transformation means that IT organizations must adapt their toolset to cover all digital experiences, beyond just the end users’. Today’s businesses can no longer focus solely on the digital interactions they manage with employees or customers; they must now contend with non-traditional factors. Whether it's the power of brand to make or break a company, the need to monitor across all locations 24/7, or the ability to proactively resolve issues, companies must adapt to...