|By Ray Camden||
|August 23, 2002 12:00 AM EDT||
Because ColdFusion components are such a new feature, developers may not yet have a good idea of what constitutes best practices.
This article attempts to rectify that situation by enumerating a set of guidelines that should be used when designing and working with CFCs, one of the most interesting new features of ColdFusion MX. Bear in mind that because they're so new, even experienced developers are debating what makes sense as a "best practice." These types of articles are always a matter of contention. I encourage you to contact me or discuss the article on any of the public lists, such as this magazine's CFDJ-List. The best way we as developers can improve our own code is by discussing our methods with others. With that in mind, let's begin...
Normally a CFC is composed of a large set of methods. Let's discuss a few things to remember when building methods.
By default, all CFC methods have an access="public" setting. A method can have four different types of access. Public means that the method can be called from the local server or from instances of the CFC. The other settings are private, package, and remote. Private methods can be called only from other methods in the CFC itself. Package methods are those that can be called from other CFCs in the same package. Remote, the most open setting, can be called from any source, including remote servers and Flash files.
It's important that you remember the default setting of "public." While it's not as open as "remote," it may not be what you intend when designing your CFC. A simple way to handle this is to set all methods in the CFC to "private." This means your methods will be as secure as possible. "Open" up your methods only on a case by case basis. If you want to be truly anal (and when it comes to security, you can't be too anal), follow this practice even when you're "really, really" sure the method will be used publicly. Wait until you actually code the CFM that will call the CFC's method. At that point you can change the method being called.
The CFFUNCTION tag takes multiple attributes, many of which are optional. It's best to explicitly set most, or all, of them. At its basic level, CFFUNCTION needs a "name" attribute. However, each of the following attributes should be passed:
Let's take a look at a method with the barest essentials set:
<cffunction name="cartTotal">Now compare this to a method with most of the optional attributes set. It's much clearer what the method is doing and how it will return information.
... method code ...
<cffunction name="cartTotal"" output="false" access="private"
hint="This method calculates the total
price of all the items in the shopping cart.
It simply loops over the cart and multiplies
item price by quantity.">
We can also apply this same principle to the CFARGUMENT tag. CFARGUMENT, like CFFUNCTION, requires only the "name" attribute. However, you can - and should - pass the following optional arguments:
Once again, let's take a look at a method that doesn't use these optional attributes:
<cffunction name="cartTotal">Now consider the version in Listing 1. As you can see, the second version of the method is much clearer about what exactly it does.
... method code ...
Output vs Return
When calling a method on a CFC, you can display the output in multiple ways. The method itself can CFOUTPUT data or it can return the data to the caller. You should never CFOUTPUT. Instead, data should be returned by using the CFRETURN tag. There are a number of reasons for this. If you ever encounter a case where you don't want the result of the method displayed immediately (maybe you want to store the result in a database), you'll have to reengineer your method and any calls to it (unless you use CFSAVECONTENT to suppress the output).
Another reason not to use CF OUTPUT is because of a bug with persistent components. If you store an instance of a component in a persistent scope (like the Session scope), and if you call a method that outputs instead of returns data, you'll only be able to call it once. Any subsequent call will not display the output.
The most important reason not to output directly from the CFC is Flash. Any data that isn't returned from the method will not be usable from Flash applications that use your CFC. By using CFRETURN, you guarantee that it will work with both your CFML files and your Flash files.
Use the Var Scope
If you've read anything about user-defined functions, you've probably seen mention of the "Var" scope. This is a scope created specifically for the lifetime of the function. By creating data in this scope, you help ensure that a UDF doesn't accidentally overwrite variables in the template. The Var scope is just as important when working with CFC methods. Consider the following CFC method:
<cffunction name="returnFoo" output="false"This function simply sets x to 1 and y to the value of another method in the CFC, and then returns the value of x. You'd expect this method to return 1. However, guess what happens if returnGoo looks like the following:
hint="Returns the value of Foo">
<cfset x = 1>
<cfset y = returnGoo(x)>
<cffunction name="returnGoo" output="false"You might expect this to have no impact on our original function, returnFoo, but because the x value was never Var scoped, instead of getting 1 back, we get 100. To correct this we can simply add the Var qualifier to the sets in each method:
hint="Returns the value of Goo">
<cfset x = 100>
<cffunction name="returnFoo" output="false"Once this is done, calling return-Foo returns the value we expect, 1.
hint="Returns the value of Foo">
<cfset var x = 1>
<cfset var y = returnGoo(x)>
<cffunction name="returnGoo" output="false"
hint="Returns the value of Goo">
<cfset var x = 100>
Don't forget that any and all Var statements must be made before any real code. They should be placed immediately after any CFARGUMENT tag.
Another aspect of CFCs is the use of component data. This is data that persists for the lifetime of the CFC and is accessible to both the methods of the CFC and, potentially, the template using the CFC.
The This Scope
Two scopes can be used with CFCs. The first one, which will be used most of the time, is the This scope. Values can be defined in this scope just as in any other:
<cfset this.name = "Raymond">
Any variable defined in this scope is available to the calling template. For example:
<cfset theOb = createObject("component","test")>Conversely, if you pass a value to a CFC, it will automatically be placed in the This scope. Consider:
<cfset theOb = createObject("component","test")>Once the CFSET command is run, any method will have access to foo in the This scope.
<cfset theOb.foo = 1>
What are some things to consider when storing information in a CFC? Any information placed in the This scope is public. It can be read by the calling template and even changed. This is fine if you don't mind the information being manipulated. However, you may not always want that. If you have information that you want to persist in the CFC without possibly exposing it, simply leave off the This scope. Imagine the following code in a CFC:
<cfset this.name = "Raymond">This code creates two variables in the CFC. The first is a public variable called name. The second variable, id, is not public. There isn't a real name for this scope. I refer to it as a private scope. It's not the same as the Variables scope and you can't CFDUMP it, but it's a useful way to store data and keep it separate from the public variables.
<cfset id = createUUID()>
The CFPROPERTY tag, technically, serves little purpose for CFCs. Its main use is to help define return values for Web services. However, it can serve a useful purpose for CFCs as well. The first thing to remember is that the CFPROPERTY tag will not actually do anything at runtime. Consider the following line of code:
<cfproperty name="numberOfLegs" type="numeric" required="true">
While it looks like it may add a level of validation to the tag, it really just defines metadata for the CFC. In other words, it helps describe it. The only required attribute is name. Everything else simply helps describe the property. This can be useful in multiple ways. First of all, it shows up in the descriptor. Second, every attribute passed in is available via the getMetaData function. This means you could write your own validation routines. Consider the following CFPROPERTY tag:
<cfproperty name="numberOfLegs" type="numeric" required="true" range="1,8">
The range attribute isn't a real attribute, but it will show up in the metadata. It would be trivial then to write a method that validates the value for this.numberOfLegs to ensure that it falls between 1 and 8. As you can imagine, this is pretty open ended. Any attribute to CFPROPERTY can be passed and used. How it's implemented is completely up to the developer.
That's Not All, Folks...
As I said at the beginning, CFCs are a new feature. What makes sense to me, and others, at this point will seem a bit silly next year (or even a few months from now). If you have any ideas you'd like to add, or perhaps you see something you disagree with, please e-mail me. You should also visit www.CFCZone.org. This is a site run by Rob Brooks-Bilson. (It's in the same vein as www.CFLib.org.) The site will soon host free, and open source, CFCs that you can use in your own projects.
DevOps at Cloud Expo, taking place Nov 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with 19th Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The widespread success of cloud computing is driving the DevOps revolution in enterprise IT. Now as never before, development teams must communicate and collaborate in a dynamic, 24/7/365 environment. There is no time to wait for long dev...
Aug. 28, 2016 07:00 AM EDT Reads: 2,385
With so much going on in this space you could be forgiven for thinking you were always working with yesterday’s technologies. So much change, so quickly. What do you do if you have to build a solution from the ground up that is expected to live in the field for at least 5-10 years? This is the challenge we faced when we looked to refresh our existing 10-year-old custom hardware stack to measure the fullness of trash cans and compactors.
Aug. 28, 2016 02:00 AM EDT Reads: 1,769
The emerging Internet of Everything creates tremendous new opportunities for customer engagement and business model innovation. However, enterprises must overcome a number of critical challenges to bring these new solutions to market. In his session at @ThingsExpo, Michael Martin, CTO/CIO at nfrastructure, outlined these key challenges and recommended approaches for overcoming them to achieve speed and agility in the design, development and implementation of Internet of Everything solutions wi...
Aug. 28, 2016 01:30 AM EDT Reads: 2,090
Cloud computing is being adopted in one form or another by 94% of enterprises today. Tens of billions of new devices are being connected to The Internet of Things. And Big Data is driving this bus. An exponential increase is expected in the amount of information being processed, managed, analyzed, and acted upon by enterprise IT. This amazing is not part of some distant future - it is happening today. One report shows a 650% increase in enterprise data by 2020. Other estimates are even higher....
Aug. 28, 2016 01:00 AM EDT Reads: 2,966
Today we can collect lots and lots of performance data. We build beautiful dashboards and even have fancy query languages to access and transform the data. Still performance data is a secret language only a couple of people understand. The more business becomes digital the more stakeholders are interested in this data including how it relates to business. Some of these people have never used a monitoring tool before. They have a question on their mind like “How is my application doing” but no id...
Aug. 28, 2016 12:15 AM EDT Reads: 1,832
The 19th International Cloud Expo has announced that its Call for Papers is open. Cloud Expo, to be held November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA, brings together Cloud Computing, Big Data, Internet of Things, DevOps, Digital Transformation, Microservices and WebRTC to one location. With cloud computing driving a higher percentage of enterprise IT budgets every year, it becomes increasingly important to plant your flag in this fast-expanding business opportuni...
Aug. 27, 2016 11:00 PM EDT Reads: 4,004
Identity is in everything and customers are looking to their providers to ensure the security of their identities, transactions and data. With the increased reliance on cloud-based services, service providers must build security and trust into their offerings, adding value to customers and improving the user experience. Making identity, security and privacy easy for customers provides a unique advantage over the competition.
Aug. 27, 2016 08:45 PM EDT Reads: 2,357
19th Cloud Expo, taking place November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA, will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud strategy. Meanwhile, 94% of enterpri...
Aug. 27, 2016 06:00 PM EDT Reads: 3,104
Smart Cities are here to stay, but for their promise to be delivered, the data they produce must not be put in new siloes. In his session at @ThingsExpo, Mathias Herberts, Co-founder and CTO of Cityzen Data, will deep dive into best practices that will ensure a successful smart city journey.
Aug. 27, 2016 05:15 PM EDT Reads: 1,585
SYS-CON Events announced today that 910Telecom will exhibit at the 19th International Cloud Expo, which will take place on November 1–3, 2016, at the Santa Clara Convention Center in Santa Clara, CA. Housed in the classic Denver Gas & Electric Building, 910 15th St., 910Telecom is a carrier-neutral telecom hotel located in the heart of Denver. Adjacent to CenturyLink, AT&T, and Denver Main, 910Telecom offers connectivity to all major carriers, Internet service providers, Internet backbones and ...
Aug. 27, 2016 05:00 PM EDT Reads: 1,889
There is growing need for data-driven applications and the need for digital platforms to build these apps. In his session at 19th Cloud Expo, Muddu Sudhakar, VP and GM of Security & IoT at Splunk, will cover different PaaS solutions and Big Data platforms that are available to build applications. In addition, AI and machine learning are creating new requirements that developers need in the building of next-gen apps. The next-generation digital platforms have some of the past platform needs a...
Aug. 27, 2016 04:00 PM EDT Reads: 609
SYS-CON Events announced today Telecom Reseller has been named “Media Sponsor” of SYS-CON's 19th International Cloud Expo, which will take place on November 1–3, 2016, at the Santa Clara Convention Center in Santa Clara, CA. 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.
Aug. 27, 2016 03:15 PM EDT Reads: 787
I wanted to gather all of my Internet of Things (IOT) blogs into a single blog (that I could later use with my University of San Francisco (USF) Big Data “MBA” course). However as I started to pull these blogs together, I realized that my IOT discussion lacked a vision; it lacked an end point towards which an organization could drive their IOT envisioning, proof of value, app dev, data engineering and data science efforts. And I think that the IOT end point is really quite simple…
Aug. 27, 2016 12:45 PM EDT Reads: 2,357
Internet of @ThingsExpo, taking place November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with 19th 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 devices - comp...
Aug. 27, 2016 12:30 PM EDT Reads: 3,628
Data is the fuel that drives the machine learning algorithmic engines and ultimately provides the business value. In his session at Cloud Expo, Ed Featherston, a director and senior enterprise architect at Collaborative Consulting, will discuss the key considerations around quality, volume, timeliness, and pedigree that must be dealt with in order to properly fuel that engine.
Aug. 27, 2016 10:15 AM EDT Reads: 1,931
Pulzze Systems was happy to participate in such a premier event and thankful to be receiving the winning investment and global network support from G-Startup Worldwide. It is an exciting time for Pulzze to showcase the effectiveness of innovative technologies and enable them to make the world smarter and better. The reputable contest is held to identify promising startups around the globe that are assured to change the world through their innovative products and disruptive technologies. There w...
Aug. 27, 2016 07:45 AM EDT Reads: 699
Personalization has long been the holy grail of marketing. Simply stated, communicate the most relevant offer to the right person and you will increase sales. To achieve this, you must understand the individual. Consequently, digital marketers developed many ways to gather and leverage customer information to deliver targeted experiences. In his session at @ThingsExpo, Lou Casal, Founder and Principal Consultant at Practicala, discussed how the Internet of Things (IoT) has accelerated our abil...
Aug. 27, 2016 02:30 AM EDT Reads: 2,033
Is the ongoing quest for agility in the data center forcing you to evaluate how to be a part of infrastructure automation efforts? As organizations evolve toward bimodal IT operations, they are embracing new service delivery models and leveraging virtualization to increase infrastructure agility. Therefore, the network must evolve in parallel to become equally agile. Read this essential piece of Gartner research for recommendations on achieving greater agility.
Aug. 25, 2016 05:15 PM EDT Reads: 842
SYS-CON Events announced today that Venafi, the Immune System for the Internet™ and the leading provider of Next Generation Trust Protection, will exhibit at @DevOpsSummit at 19th International Cloud Expo, which will take place on November 1–3, 2016, at the Santa Clara Convention Center in Santa Clara, CA. Venafi is the Immune System for the Internet™ that protects the foundation of all cybersecurity – cryptographic keys and digital certificates – so they can’t be misused by bad guys in attacks...
Aug. 25, 2016 01:00 PM EDT Reads: 2,664
For basic one-to-one voice or video calling solutions, WebRTC has proven to be a very powerful technology. Although WebRTC’s core functionality is to provide secure, real-time p2p media streaming, leveraging native platform features and server-side components brings up new communication capabilities for web and native mobile applications, allowing for advanced multi-user use cases such as video broadcasting, conferencing, and media recording.
Aug. 25, 2016 08:45 AM EDT Reads: 2,193