|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.
SYS-CON Events announced today that Cloudbric, a leading website security provider, 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. Cloudbric is an elite full service website protection solution specifically designed for IT novices, entrepreneurs, and small and medium businesses. First launched in 2015, Cloudbric is based on the enterprise level Web Application Firewall by Penta Security Sys...
Oct. 28, 2016 03:15 PM EDT Reads: 1,378
Virgil consists of an open-source encryption library, which implements Cryptographic Message Syntax (CMS) and Elliptic Curve Integrated Encryption Scheme (ECIES) (including RSA schema), a Key Management API, and a cloud-based Key Management Service (Virgil Keys). The Virgil Keys Service consists of a public key service and a private key escrow service.
Oct. 28, 2016 02:30 PM EDT Reads: 1,249
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.
Oct. 28, 2016 02:15 PM EDT Reads: 4,020
SYS-CON Events announced today that MathFreeOn 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. MathFreeOn is Software as a Service (SaaS) used in Engineering and Math education. Write scripts and solve math problems online. MathFreeOn provides online courses for beginners or amateurs who have difficulties in writing scripts. In accordance with various mathematical topics, there are more tha...
Oct. 28, 2016 02:00 PM EDT Reads: 1,219
In an era of historic innovation fueled by unprecedented access to data and technology, the low cost and risk of entering new markets has leveled the playing field for business. Today, any ambitious innovator can easily introduce a new application or product that can reinvent business models and transform the client experience. In their Day 2 Keynote at 19th Cloud Expo, Mercer Rowe, IBM Vice President of Strategic Alliances, and Raejeanne Skillern, Intel Vice President of Data Center Group and ...
Oct. 28, 2016 01:45 PM EDT Reads: 1,716
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.
Oct. 28, 2016 01:30 PM EDT Reads: 5,175
@ThingsExpo has been named the Top 5 Most Influential Internet of Things Brand by Onalytica in the ‘The Internet of Things Landscape 2015: Top 100 Individuals and Brands.' Onalytica analyzed Twitter conversations around the #IoT debate to uncover the most influential brands and individuals driving the conversation. Onalytica captured data from 56,224 users. The PageRank based methodology they use to extract influencers on a particular topic (tweets mentioning #InternetofThings or #IoT in this ...
Oct. 28, 2016 01:15 PM EDT Reads: 8,655
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...
Oct. 28, 2016 01:00 PM EDT Reads: 2,418
"We've discovered that after shows 80% if leads that people get, 80% of the conversations end up on the show floor, meaning people forget about it, people forget who they talk to, people forget that there are actual business opportunities to be had here so we try to help out and keep the conversations going," explained Jeff Mesnik, Founder and President of ContentMX, in this SYS-CON.tv interview at 18th Cloud Expo, held June 7-9, 2016, at the Javits Center in New York City, NY.
Oct. 28, 2016 01:00 PM EDT Reads: 3,725
Bert Loomis was a visionary. This general session will highlight how Bert Loomis and people like him inspire us to build great things with small inventions. In their general session at 19th Cloud Expo, Harold Hannon, Architect at IBM Bluemix, and Michael O'Neill, Strategic Business Development at Nvidia, will discuss the accelerating pace of AI development and how IBM Cloud and NVIDIA are partnering to bring AI capabilities to "every day," on-demand. They will also review two "free infrastruct...
Oct. 28, 2016 12:30 PM EDT Reads: 321
Intelligent machines are here. Robots, self-driving cars, drones, bots and many IoT devices are becoming smarter with Machine Learning. In her session at @ThingsExpo, Sudha Jamthe, CEO of IoTDisruptions.com, will discuss the next wave of business disruption at the junction of IoT and AI, impacting many industries and set to change our lives, work and world as we know it.
Oct. 28, 2016 12:30 PM EDT Reads: 645
More and more brands have jumped on the IoT bandwagon. We have an excess of wearables – activity trackers, smartwatches, smart glasses and sneakers, and more that track seemingly endless datapoints. However, most consumers have no idea what “IoT” means. Creating more wearables that track data shouldn't be the aim of brands; delivering meaningful, tangible relevance to their users should be. We're in a period in which the IoT pendulum is still swinging. Initially, it swung toward "smart for smar...
Oct. 28, 2016 12:15 PM EDT Reads: 1,306
In past @ThingsExpo presentations, Joseph di Paolantonio has explored how various Internet of Things (IoT) and data management and analytics (DMA) solution spaces will come together as sensor analytics ecosystems. This year, in his session at @ThingsExpo, Joseph di Paolantonio from DataArchon, will be adding the numerous Transportation areas, from autonomous vehicles to “Uber for containers.” While IoT data in any one area of Transportation will have a huge impact in that area, combining sensor...
Oct. 28, 2016 12:00 PM EDT Reads: 1,238
In his general session at 19th Cloud Expo, Manish Dixit, VP of Product and Engineering at Dice, will discuss 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 a...
Oct. 28, 2016 12:00 PM EDT Reads: 955
Join IBM November 2 at 19th Cloud Expo at the Santa Clara Convention Center in Santa Clara, CA, and learn how to go beyond multi-speed it to bring agility to traditional enterprise applications. Technology innovation is the driving force behind modern business and enterprises must respond by increasing the speed and efficiency of software delivery. The challenge is that existing enterprise applications are expensive to develop and difficult to modernize. This often results in what Gartner calls...
Oct. 28, 2016 11:30 AM EDT Reads: 337
The explosion of new web/cloud/IoT-based applications and the data they generate are transforming our world right before our eyes. In this rush to adopt these new technologies, organizations are often ignoring fundamental questions concerning who owns the data and failing to ask for permission to conduct invasive surveillance of their customers. Organizations that are not transparent about how their systems gather data telemetry without offering shared data ownership risk product rejection, regu...
Oct. 28, 2016 11:00 AM EDT Reads: 377
Although it has gained significant traction in the consumer space, IoT is still in the early stages of adoption in enterprises environments. However, many companies are working on initiatives like Industry 4.0 that includes IoT as one of the key disruptive technologies expected to reshape businesses of tomorrow. The key challenges will be availability, robustness and reliability of networks that connect devices in a business environment. Software Defined Wide Area Network (SD-WAN) is expected to...
Oct. 28, 2016 11:00 AM EDT Reads: 2,287
The Internet of Things (IoT), in all its myriad manifestations, has great potential. Much of that potential comes from the evolving data management and analytic (DMA) technologies and processes that allow us to gain insight from all of the IoT data that can be generated and gathered. This potential may never be met as those data sets are tied to specific industry verticals and single markets, with no clear way to use IoT data and sensor analytics to fulfill the hype being given the IoT today.
Oct. 28, 2016 10:30 AM EDT Reads: 2,964
@ThingsExpo has been named the Top 5 Most Influential M2M Brand by Onalytica in the ‘Machine to Machine: Top 100 Influencers and Brands.' Onalytica analyzed the online debate on M2M by looking at over 85,000 tweets to provide the most influential individuals and brands that drive the discussion. According to Onalytica the "analysis showed a very engaged community with a lot of interactive tweets. The M2M discussion seems to be more fragmented and driven by some of the major brands present in the...
Oct. 28, 2016 09:15 AM EDT Reads: 11,640
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...
Oct. 28, 2016 08:00 AM EDT Reads: 5,105