Welcome!

Machine Learning Authors: Pat Romanski, Elizabeth White, Yeshim Deniz, Corey Roth, Liz McMillan

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

@CloudExpo Stories
"DivvyCloud as a company set out to help customers automate solutions to the most common cloud problems," noted Jeremy Snyder, VP of Business Development at DivvyCloud, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
CI/CD is conceptually straightforward, yet often technically intricate to implement since it requires time and opportunities to develop intimate understanding on not only DevOps processes and operations, but likely product integrations with multiple platforms. This session intends to bridge the gap by offering an intense learning experience while witnessing the processes and operations to build from zero to a simple, yet functional CI/CD pipeline integrated with Jenkins, Github, Docker and Azure...
"Our strategy is to focus on the hyperscale providers - AWS, Azure, and Google. Over the last year we saw that a lot of developers need to learn how to do their job in the cloud and we see this DevOps movement that we are catering to with our content," stated Alessandro Fasan, Head of Global Sales at Cloud Academy, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
As organizations shift towards IT-as-a-service models, the need for managing and protecting data residing across physical, virtual, and now cloud environments grows with it. Commvault can ensure protection, access and E-Discovery of your data – whether in a private cloud, a Service Provider delivered public cloud, or a hybrid cloud environment – across the heterogeneous enterprise. In his general session at 18th Cloud Expo, Randy De Meno, Chief Technologist - Windows Products and Microsoft Part...
DXWorldEXPO LLC announced today that ICC-USA, a computer systems integrator and server manufacturing company focused on developing products and product appliances, will exhibit at the 22nd International CloudEXPO | DXWorldEXPO. DXWordEXPO New York 2018, colocated with CloudEXPO New York 2018 will be held November 11-13, 2018, in New York City. ICC is a computer systems integrator and server manufacturing company focused on developing products and product appliances to meet a wide range of ...
Andi Mann, Chief Technology Advocate at Splunk, is an accomplished digital business executive with extensive global expertise as a strategist, technologist, innovator, marketer, and communicator. For over 30 years across five continents, he has built success with Fortune 500 corporations, vendors, governments, and as a leading research analyst and consultant.
JETRO showcased Japan Digital Transformation Pavilion at SYS-CON's 21st International Cloud Expo® at the Santa Clara Convention Center in Santa Clara, CA. The Japan External Trade Organization (JETRO) is a non-profit organization that provides business support services to companies expanding to Japan. With the support of JETRO's dedicated staff, clients can incorporate their business; receive visa, immigration, and HR support; find dedicated office space; identify local government subsidies; get...
René Bostic is the Technical VP of the IBM Cloud Unit in North America. Enjoying her career with IBM during the modern millennial technological era, she is an expert in cloud computing, DevOps and emerging cloud technologies such as Blockchain. Her strengths and core competencies include a proven record of accomplishments in consensus building at all levels to assess, plan, and implement enterprise and cloud computing solutions. René is a member of the Society of Women Engineers (SWE) and a m...
In this presentation, you will learn first hand what works and what doesn't while architecting and deploying OpenStack. Some of the topics will include:- best practices for creating repeatable deployments of OpenStack- multi-site considerations- how to customize OpenStack to integrate with your existing systems and security best practices.
Explosive growth in connected devices. Enormous amounts of data for collection and analysis. Critical use of data for split-second decision making and actionable information. All three are factors in making the Internet of Things a reality. Yet, any one factor would have an IT organization pondering its infrastructure strategy. How should your organization enhance its IT framework to enable an Internet of Things implementation? In his session at @ThingsExpo, James Kirkland, Red Hat's Chief Archi...
Digital transformation has increased the pace of business creating a productivity divide between the technology haves and have nots. Managing financial information on spreadsheets and piecing together insight from numerous disconnected systems is no longer an option. Rapid market changes and aggressive competition are motivating business leaders to reevaluate legacy technology investments in search of modern technologies to achieve greater agility, reduced costs and organizational efficiencies. ...
"With Digital Experience Monitoring what used to be a simple visit to a web page has exploded into app on phones, data from social media feeds, competitive benchmarking - these are all components that are only available because of some type of digital asset," explained Leo Vasiliou, Director of Web Performance Engineering at Catchpoint Systems, in this SYS-CON.tv interview at DevOps Summit at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
In his general session at 19th Cloud Expo, Manish Dixit, VP of Product and Engineering at Dice, discussed how Dice leverages data insights and tools to help both tech professionals and recruiters better understand how skills relate to each other and which skills are in high demand using interactive visualizations and salary indicator tools to maximize earning potential. Manish Dixit is VP of Product and Engineering at Dice. As the leader of the Product, Engineering and Data Sciences team at D...
It is ironic, but perhaps not unexpected, that many organizations who want the benefits of using an Agile approach to deliver software use a waterfall approach to adopting Agile practices: they form plans, they set milestones, and they measure progress by how many teams they have engaged. Old habits die hard, but like most waterfall software projects, most waterfall-style Agile adoption efforts fail to produce the results desired. The problem is that to get the results they want, they have to ch...
Organizations planning enterprise data center consolidation and modernization projects are faced with a challenging, costly reality. Requirements to deploy modern, cloud-native applications simultaneously with traditional client/server applications are almost impossible to achieve with hardware-centric enterprise infrastructure. Compute and network infrastructure are fast moving down a software-defined path, but storage has been a laggard. Until now.
Without a clear strategy for cost control and an architecture designed with cloud services in mind, costs and operational performance can quickly get out of control. To avoid multiple architectural redesigns requires extensive thought and planning. Boundary (now part of BMC) launched a new public-facing multi-tenant high resolution monitoring service on Amazon AWS two years ago, facing challenges and learning best practices in the early days of the new service.
HyperConvergence came to market with the objective of being simple, flexible and to help drive down operating expenses. It reduced the footprint by bundling the compute/storage/network into one box. This brought a new set of challenges as the HyperConverged vendors are very focused on their own proprietary building blocks. If you want to scale in a certain way, let's say you identified a need for more storage and want to add a device that is not sold by the HyperConverged vendor, forget about it...
Digital Transformation is much more than a buzzword. The radical shift to digital mechanisms for almost every process is evident across all industries and verticals. This is often especially true in financial services, where the legacy environment is many times unable to keep up with the rapidly shifting demands of the consumer. The constant pressure to provide complete, omnichannel delivery of customer-facing solutions to meet both regulatory and customer demands is putting enormous pressure on...
The best way to leverage your CloudEXPO | DXWorldEXPO presence as a sponsor and exhibitor is to plan your news announcements around our events. The press covering CloudEXPO | DXWorldEXPO 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 CloudEXPO. Product announcements during our show provide your company with the most reach through our targeted audienc...
@DevOpsSummit at Cloud Expo, taking place November 12-13 in New York City, NY, is co-located with 22nd international CloudEXPO | first international DXWorldEXPO and will feature technical sessions from a rock star conference faculty and the leading industry players in the world.
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!