Welcome!

Machine Learning Authors: William Schmarzo, Elizabeth White, Liz McMillan, Pat Romanski, James Carlini

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
"MobiDev is a software development company and we do complex, custom software development for everybody from entrepreneurs to large enterprises," explained Alan Winters, U.S. Head of Business Development at MobiDev, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
In his session at 21st Cloud Expo, Carl J. Levine, Senior Technical Evangelist for NS1, will objectively discuss how DNS is used to solve Digital Transformation challenges in large SaaS applications, CDNs, AdTech platforms, and other demanding use cases. Carl J. Levine is the Senior Technical Evangelist for NS1. A veteran of the Internet Infrastructure space, he has over a decade of experience with startups, networking protocols and Internet infrastructure, combined with the unique ability to it...
Vulnerability management is vital for large companies that need to secure containers across thousands of hosts, but many struggle to understand how exposed they are when they discover a new high security vulnerability. In his session at 21st Cloud Expo, John Morello, CTO of Twistlock, addressed this pressing concern by introducing the concept of the “Vulnerability Risk Tree API,” which brings all the data together in a simple REST endpoint, allowing companies to easily grasp the severity of the ...
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...
In his session at 21st Cloud Expo, James Henry, Co-CEO/CTO of Calgary Scientific Inc., introduced you to the challenges, solutions and benefits of training AI systems to solve visual problems with an emphasis on improving AIs with continuous training in the field. He explored applications in several industries and discussed technologies that allow the deployment of advanced visualization solutions to the cloud.
Enterprises are adopting Kubernetes to accelerate the development and the delivery of cloud-native applications. However, sharing a Kubernetes cluster between members of the same team can be challenging. And, sharing clusters across multiple teams is even harder. Kubernetes offers several constructs to help implement segmentation and isolation. However, these primitives can be complex to understand and apply. As a result, it’s becoming common for enterprises to end up with several clusters. Thi...
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, discussed how data centers of the future will be managed, how the p...
"NetApp is known as a data management leader but we do a lot more than just data management on-prem with the data centers of our customers. We're also big in the hybrid cloud," explained Wes Talbert, Principal Architect at NetApp, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
"Space Monkey by Vivent Smart Home is a product that is a distributed cloud-based edge storage network. Vivent Smart Home, our parent company, is a smart home provider that places a lot of hard drives across homes in North America," explained JT Olds, Director of Engineering, and Brandon Crowfeather, Product Manager, at Vivint Smart Home, in this SYS-CON.tv interview at @ThingsExpo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
The question before companies today is not whether to become intelligent, it’s a question of how and how fast. The key is to adopt and deploy an intelligent application strategy while simultaneously preparing to scale that intelligence. In her session at 21st Cloud Expo, Sangeeta Chakraborty, Chief Customer Officer at Ayasdi, provided a tactical framework to become a truly intelligent enterprise, including how to identify the right applications for AI, how to build a Center of Excellence to oper...
"IBM is really all in on blockchain. We take a look at sort of the history of blockchain ledger technologies. It started out with bitcoin, Ethereum, and IBM evaluated these particular blockchain technologies and found they were anonymous and permissionless and that many companies were looking for permissioned blockchain," stated René Bostic, Technical VP of the IBM Cloud Unit in North America, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Conventi...
Coca-Cola’s Google powered digital signage system lays the groundwork for a more valuable connection between Coke and its customers. Digital signs pair software with high-resolution displays so that a message can be changed instantly based on what the operator wants to communicate or sell. In their Day 3 Keynote at 21st Cloud Expo, Greg Chambers, Global Group Director, Digital Innovation, Coca-Cola, and Vidya Nagarajan, a Senior Product Manager at Google, discussed how from store operations and ...
"Infoblox does DNS, DHCP and IP address management for not only enterprise networks but cloud networks as well. Customers are looking for a single platform that can extend not only in their private enterprise environment but private cloud, public cloud, tracking all the IP space and everything that is going on in that environment," explained Steve Salo, Principal Systems Engineer at Infoblox, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Conventio...
Large industrial manufacturing organizations are adopting the agile principles of cloud software companies. The industrial manufacturing development process has not scaled over time. Now that design CAD teams are geographically distributed, centralizing their work is key. With large multi-gigabyte projects, outdated tools have stifled industrial team agility, time-to-market milestones, and impacted P&L stakeholders.
"ZeroStack is a startup in Silicon Valley. We're solving a very interesting problem around bringing public cloud convenience with private cloud control for enterprises and mid-size companies," explained Kamesh Pemmaraju, VP of Product Management at ZeroStack, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
"We're focused on how to get some of the attributes that you would expect from an Amazon, Azure, Google, and doing that on-prem. We believe today that you can actually get those types of things done with certain architectures available in the market today," explained Steve Conner, VP of Sales at Cloudistics, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
"Codigm is based on the cloud and we are here to explore marketing opportunities in America. Our mission is to make an ecosystem of the SW environment that anyone can understand, learn, teach, and develop the SW on the cloud," explained Sung Tae Ryu, CEO of Codigm, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
Data scientists must access high-performance computing resources across a wide-area network. To achieve cloud-based HPC visualization, researchers must transfer datasets and visualization results efficiently. HPC clusters now compute GPU-accelerated visualization in the cloud cluster. To efficiently display results remotely, a high-performance, low-latency protocol transfers the display from the cluster to a remote desktop. Further, tools to easily mount remote datasets and efficiently transfer...
High-velocity engineering teams are applying not only continuous delivery processes, but also lessons in experimentation from established leaders like Amazon, Netflix, and Facebook. These companies have made experimentation a foundation for their release processes, allowing them to try out major feature releases and redesigns within smaller groups before making them broadly available. In his session at 21st Cloud Expo, Brian Lucas, Senior Staff Engineer at Optimizely, discussed how by using ne...
Gemini is Yahoo’s native and search advertising platform. To ensure the quality of a complex distributed system that spans multiple products and components and across various desktop websites and mobile app and web experiences – both Yahoo owned and operated and third-party syndication (supply), with complex interaction with more than a billion users and numerous advertisers globally (demand) – it becomes imperative to automate a set of end-to-end tests 24x7 to detect bugs and regression. In th...