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
Mobile device usage has increased exponentially during the past several years, as consumers rely on handhelds for everything from news and weather to banking and purchases. What can we expect in the next few years? The way in which we interact with our devices will fundamentally change, as businesses leverage Artificial Intelligence. We already see this taking shape as businesses leverage AI for cost savings and customer responsiveness. This trend will continue, as AI is used for more sophistica...
Real IoT production deployments running at scale are collecting sensor data from hundreds / thousands / millions of devices. The goal is to take business-critical actions on the real-time data and find insights from stored datasets. In his session at @ThingsExpo, John Walicki, Watson IoT Developer Advocate at IBM Cloud, will provide a fast-paced developer journey that follows the IoT sensor data from generation, to edge gateway, to edge analytics, to encryption, to the IBM Bluemix cloud, to Wa...
What is the best strategy for selecting the right offshore company for your business? In his session at 21st Cloud Expo, Alan Winters, U.S. Head of Business Development at MobiDev, will discuss the things to look for - positive and negative - in evaluating your options. He will also discuss how to maximize productivity with your offshore developers. Before you start your search, clearly understand your business needs and how that impacts software choices.
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 Fusic 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. Fusic Co. provides mocks as virtual IoT devices. You can customize mocks, and get any amount of data at any time in your test. For more information, visit https://fusic.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.
SYS-CON Events announced today that Enroute Lab 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. Enroute Lab is an industrial design, research and development company of unmanned robotic vehicle system. For more information, please visit http://elab.co.jp/.
SYS-CON Events announced today that Mobile Create USA 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. Mobile Create USA Inc. is an MVNO-based business model that uses portable communication devices and cellular-based infrastructure in the development, sales, operation and mobile communications systems incorporating GPS capabi...
SYS-CON Events announced today that Keisoku Research Consultant Co. 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. Keisoku Research Consultant, Co. offers research and consulting in a wide range of civil engineering-related fields from information construction to preservation of cultural properties. For more information, vi...
There is huge complexity in implementing a successful digital business that requires efficient on-premise and cloud back-end infrastructure, IT and Internet of Things (IoT) data, analytics, Machine Learning, Artificial Intelligence (AI) and Digital Applications. In the data center alone, there are physical and virtual infrastructures, multiple operating systems, multiple applications and new and emerging business and technological paradigms such as cloud computing and XaaS. And then there are pe...
SYS-CON Events announced today that Interface Corporation 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. Interface Corporation is a company developing, manufacturing and marketing high quality and wide variety of industrial computers and interface modules such as PCIs and PCI express. For more information, visit http://www.i...
SYS-CON Events announced today that SIGMA Corporation 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. uLaser flow inspection device from the Japanese top share to Global Standard! Then, make the best use of data to flip to next page. For more information, visit http://www.sigma-k.co.jp/en/.
SYS-CON Events announced today that B2Cloud 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. B2Cloud specializes in IoT devices for preventive and predictive maintenance in any kind of equipment retrieving data like Energy consumption, working time, temperature, humidity, pressure, etc.
Agile has finally jumped the technology shark, expanding outside the software world. Enterprises are now increasingly adopting Agile practices across their organizations in order to successfully navigate the disruptive waters that threaten to drown them. In our quest for establishing change as a core competency in our organizations, this business-centric notion of Agile is an essential component of Agile Digital Transformation. In the years since the publication of the Agile Manifesto, the conn...
While some developers care passionately about how data centers and clouds are architected, for most, it is only the end result that matters. To the majority of companies, technology exists to solve a business problem, and only delivers value when it is solving that problem. 2017 brings the mainstream adoption of containers for production workloads. In his session at 21st Cloud Expo, Ben McCormack, VP of Operations at Evernote, will discuss how data centers of the future will be managed, how th...
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 em...
SYS-CON Events announced today that Nihon Micron 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. Nihon Micron Co., Ltd. strives for technological innovation to establish high-density, high-precision processing technology for providing printed circuit board and metal mount RFID tags used for communication devices. For more inf...
SYS-CON Events announced today that Suzuki 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. Suzuki Inc. is a semiconductor-related business, including sales of consuming parts, parts repair, and maintenance for semiconductor manufacturing machines, etc. It is also a health care business providing experimental research for...
SYS-CON Events announced today that Ryobi Systems 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. Ryobi Systems Co., Ltd., as an information service company, specialized in business support for local governments and medical industry. We are challenging to achive the precision farming with AI. For more information, visit http:...
SYS-CON Events announced today that Daiya Industry 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. Daiya Industry specializes in orthotic support systems and assistive devices with pneumatic artificial muscles in order to contribute to an extended healthy life expectancy. For more information, please visit https://www.daiyak...