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, Adobe Flex

ColdFusion: Article

Inheritance in ColdFusion: Code Reuse for CFCs

When it comes to code, less is more

But how are a CFC's properties and methods created? When the instance of the CFC is created, the "pseudo-constructor" of the CFC is called. Effectively, this means that all the code in the CFC that defines methods is used to create the object's methods and that all other code in the CFC, including any code that creates the object's properties, is executed.

Once an object has been created from a CFC, it and its public properties and methods can be referenced. By assigning the object to a variable, it and its public properties and methods can be referenced an unlimited number of times during the life of that variable. In line 1 of callsimple.cfm, we see that the object created from simple.cfc is assigned to a variable named myObj. Because no scope is declared for myObj, it is placed in the Variables scope. On the fourth line of callsimple.cfm, we see the public myVar property of the myObj instance of simple.cfc being referenced, and on the fifth line of callsimple.cfm, we see the public myMethod method of that same myObj instance of simple.cfc being called. Referencing an object's public properties and methods is as simple as using the variable name to which the object was assigned followed by a period (a.k.a. "dot") and then the name of the property or method.

When calling a method of an object, we also must include a pair of parentheses after the method name. Inside those parentheses we must include, if any for the given method, a comma-delimited list of the arguments to be passed to the method. There are other ways to pass arguments to methods, but for simplicity's sake we won't cover those in this article.

Now that we know what is going on in callsimple.cfm, let's look at its output:

text output
statement
string

The first line of the output results from simply creating an instance of simple.cfc on the first line of callsimple.cfm and the resultant pseudo-constructor execution of all code in simple.cfc. The second line of the output results from referencing the public myVar property of myObj on the fourth line of callsimple.cfm. Finally, the third line of the output results from referencing the public myMethod method of myObj on the fifth line of callsimple.cfm.

With a basic understanding of CFCs in place, let's move on to the purpose of this article: reusing code with CFCs. As mentioned earlier, we can reuse code in CFCs not only via all the standard CFML code reuse methods - including files, calling custom tags, and calling user-defined functions - but also via inheritance. But what exactly is inheritance?

CFCs and Inheritance
In the real world, inheritance involves one entity gaining things as the result of a relationship with another entity. Inheritance in CFCs is very similar: one CFC gains things (specifically, CFML code) as the result of a relationship with another CFC. We call a CFC that inherits from another a "child CFC" and we call the CFC from which that child inherits a "parent CFC." CFML inheritance is virtual, meaning both the child CFC and the parent CFC contain the complete CFML code of the parent CFC, without duplication of the CFML code of the parent CFC in the child CFC file.

Why is inheritance useful? Because it allows us to write code in one CFC and then use that code in numerous other CFCs. Thus, we can write that CFML code one time and have it virtually contained in an unlimited number of CFCs through inheritance. By writing that CFML only one time, it's less likely we will write bugs into it and, should a bug be discovered in it or should a requirement for its functionality change, we need only modify a single instance of the code.

Now that we have an understanding of CFC inheritance, let's take a look at how it's used in a file called exsimple.cfc:

<cfcomponent extends="simple">
    <cffunction name="newMethod">
       <cfreturn "newstring">
    </cffunction>
</cfcomponent>

Note the difference between the opening <cfcomponent> tag of simple.cfc and the opening <cfcomponent> tag of exsimple.cfc - exsimple.cfc has 'extends="simple"' in that opening <cfcomponent> tag. The extends attribute of a CFC's <cfcomponent> tag is used to specify that CFC's parent. As such, by using 'extends="simple"' in the opening <cfcomponent> tag, we cause exsimple.cfc to virtually contain all the CFML in simple.cfc. Thus, when an instance of exsimple.cfc is created with either the CreateObject() function or the <cfobject> tag, the pseudo-constructor of simple.cfc is called, causing the CFML code contained in simple.cfc to be executed, just as if that code were located in exsimple.cfc. In addition, after an instance of exsimple.cfc has been created, we can reference on that instance any of the public properties and methods defined in simple.cfc just as if they were defined in exsimple.cfc. Let's see what this looks like in a file named callexsimple.cfm:

<cfset myObj = CreateObject("component", "exsimple")>
<cfoutput>
    <br>
    #myObj.myVar#<br>
    #myObj.myMethod()#<br>
    #myObj.newMethod()#<br>
</cfoutput>

We create an instance of exsimple.cfc. Because exsimple.cfc extends simple.cfc, we can reference the public myVar property and the public myMethod method of simple.cfc as well as the public newMethod method of exsimple.cfc. The output of callexsimple.cfm is exactly what we expect:

text output
statement
string
newstring

Now if we update simple.cfc, exsimple.cfc will automatically get the benefits of that change without being changed at all.
Because we didn't have to duplicate code from simple.cfc in order to use it in exsimple.cfc, we were able to write less code. Less code is better code because it gives us fewer places to introduce bugs and because it's easier to maintain.


More Stories By Josh Adams

Josh Adams is the developer evangelist for New Atlanta's BlueDragon family of CFML application server products. He presents on a regular basis at technical conferences and user groups throughout North America. Josh is also an active CFML developer both in his role at New Atlanta and in other endeavors.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


IoT & Smart Cities Stories
SYS-CON Events announced today that IoT Global Network has been named “Media Sponsor” of SYS-CON's @ThingsExpo, which will take place on June 6–8, 2017, at the Javits Center in New York City, NY. The IoT Global Network is a platform where you can connect with industry experts and network across the IoT community to build the successful IoT business of the future.
CloudEXPO New York 2018, colocated with DXWorldEXPO New York 2018 will be held November 11-13, 2018, in New York City and will bring together Cloud Computing, FinTech and Blockchain, Digital Transformation, Big Data, Internet of Things, DevOps, AI, Machine Learning and WebRTC to one location.
Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life settlement products to hedge funds and investment banks. After, he co-founded a revenue cycle management company where he learned about Bitcoin and eventually Ethereal. Andrew's role at ConsenSys Enterprise is a mul...
The best way to leverage your Cloud Expo presence as a sponsor and exhibitor is to plan your news announcements around our events. The press covering Cloud Expo and @ThingsExpo 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 Cloud Expo. Product announcements during our show provide your company with the most reach through our targeted audiences.
DXWorldEXPO | CloudEXPO are the world's most influential, independent events where Cloud Computing was coined and where technology buyers and vendors meet to experience and discuss the big picture of Digital Transformation and all of the strategies, tactics, and tools they need to realize their goals. Sponsors of DXWorldEXPO | CloudEXPO benefit from unmatched branding, profile building and lead generation opportunities.
Disruption, Innovation, Artificial Intelligence and Machine Learning, Leadership and Management hear these words all day every day... lofty goals but how do we make it real? Add to that, that simply put, people don't like change. But what if we could implement and utilize these enterprise tools in a fast and "Non-Disruptive" way, enabling us to glean insights about our business, identify and reduce exposure, risk and liability, and secure business continuity?
DXWorldEXPO LLC announced today that Telecom Reseller has been named "Media Sponsor" of CloudEXPO | DXWorldEXPO 2018 New York, which will take place on November 11-13, 2018 in New York City, NY. Telecom Reseller reports on Unified Communications, UCaaS, BPaaS for enterprise and SMBs. They report extensively on both customer premises based solutions such as IP-PBX as well as cloud based and hosted platforms.
Digital Transformation: Preparing Cloud & IoT Security for the Age of Artificial Intelligence. As automation and artificial intelligence (AI) power solution development and delivery, many businesses need to build backend cloud capabilities. Well-poised organizations, marketing smart devices with AI and BlockChain capabilities prepare to refine compliance and regulatory capabilities in 2018. Volumes of health, financial, technical and privacy data, along with tightening compliance requirements by...
In this Women in Technology Power Panel at 15th Cloud Expo, moderated by Anne Plese, Senior Consultant, Cloud Product Marketing at Verizon Enterprise, Esmeralda Swartz, CMO at MetraTech; Evelyn de Souza, Data Privacy and Compliance Strategy Leader at Cisco Systems; Seema Jethani, Director of Product Management at Basho Technologies; Victoria Livschitz, CEO of Qubell Inc.; Anne Hungate, Senior Director of Software Quality at DIRECTV, discussed what path they took to find their spot within the tec...
To Really Work for Enterprises, MultiCloud Adoption Requires Far Better and Inclusive Cloud Monitoring and Cost Management … But How? Overwhelmingly, even as enterprises have adopted cloud computing and are expanding to multi-cloud computing, IT leaders remain concerned about how to monitor, manage and control costs across hybrid and multi-cloud deployments. It’s clear that traditional IT monitoring and management approaches, designed after all for on-premises data centers, are falling short in ...