|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 Men & Mice, the leading global provider of DNS, DHCP and IP address management overlay solutions, will exhibit at SYS-CON's 18th International Cloud Expo®, which will take place on June 7-9, 2016, at the Javits Center in New York City, NY. The Men & Mice Suite overlay solution is already known for its powerful application in heterogeneous operating environments, enabling enterprises to scale without fuss. Building on a solid range of diverse platform support,...
Feb. 13, 2016 11:45 AM EST Reads: 267
WebSocket is effectively a persistent and fat pipe that is compatible with a standard web infrastructure; a "TCP for the Web." If you think of WebSocket in this light, there are other more hugely interesting applications of WebSocket than just simply sending data to a browser. In his session at 18th Cloud Expo, Frank Greco, Director of Technology for Kaazing Corporation, will compare other modern web connectivity methods such as HTTP/2, HTTP Streaming, Server-Sent Events and new W3C event APIs ...
Feb. 13, 2016 11:30 AM EST
Fortunately, meaningful and tangible business cases for IoT are plentiful in a broad array of industries and vertical markets. These range from simple warranty cost reduction for capital intensive assets, to minimizing downtime for vital business tools, to creating feedback loops improving product design, to improving and enhancing enterprise customer experiences. All of these business cases, which will be briefly explored in this session, hinge on cost effectively extracting relevant data from ...
Feb. 13, 2016 11:30 AM EST Reads: 153
Companies can harness IoT and predictive analytics to sustain business continuity; predict and manage site performance during emergencies; minimize expensive reactive maintenance; and forecast equipment and maintenance budgets and expenditures. Providing cost-effective, uninterrupted service is challenging, particularly for organizations with geographically dispersed operations.
Feb. 13, 2016 11:00 AM EST
There will be new vendors providing applications, middleware, and connected devices to support the thriving IoT ecosystem. This essentially means that electronic device manufacturers will also be in the software business. Many will be new to building embedded software or robust software. This creates an increased importance on software quality, particularly within the Industrial Internet of Things where business-critical applications are becoming dependent on products controlled by software. Qua...
Feb. 13, 2016 11:00 AM EST
SYS-CON Events announced today that iDevices®, the preeminent brand in the connected home industry, will exhibit at SYS-CON's 18th International Cloud Expo®, which will take place on June 7-9, 2016, at the Javits Center in New York City, NY. iDevices, the preeminent brand in the connected home industry, has a growing line of HomeKit-enabled products available at the largest retailers worldwide. Through the “Designed with iDevices” co-development program and its custom-built IoT Cloud Infrastruc...
Feb. 13, 2016 11:00 AM EST Reads: 143
Join us at Cloud Expo | @ThingsExpo 2016 – June 7-9 at the Javits Center in New York City and November 1-3 at the Santa Clara Convention Center in Santa Clara, CA – and deliver your unique message in a way that is striking and unforgettable by taking advantage of SYS-CON's unmatched high-impact, result-driven event / media packages.
Feb. 13, 2016 10:00 AM EST
As enterprises work to take advantage of Big Data technologies, they frequently become distracted by product-level decisions. In most new Big Data builds this approach is completely counter-productive: it presupposes tools that may not be a fit for development teams, forces IT to take on the burden of evaluating and maintaining unfamiliar technology, and represents a major up-front expense. In his session at @BigDataExpo at @ThingsExpo, Andrew Warfield, CTO and Co-Founder of Coho Data, will dis...
Feb. 13, 2016 09:45 AM EST Reads: 229
Silver Spring Networks, Inc. (NYSE: SSNI) extended its Internet of Things technology platform with performance enhancements to Gen5 – its fifth generation critical infrastructure networking platform. Already delivering nearly 23 million devices on five continents as one of the leading networking providers in the market, Silver Spring announced it is doubling the maximum speed of its Gen5 network to up to 2.4 Mbps, increasing computational performance by 10x, supporting simultaneous mesh communic...
Feb. 13, 2016 05:00 AM EST
Eighty percent of a data scientist’s time is spent gathering and cleaning up data, and 80% of all data is unstructured and almost never analyzed. Cognitive computing, in combination with Big Data, is changing the equation by creating data reservoirs and using natural language processing to enable analysis of unstructured data sources. This is impacting every aspect of the analytics profession from how data is mined (and by whom) to how it is delivered. This is not some futuristic vision: it's ha...
Feb. 13, 2016 04:45 AM EST Reads: 472
The cloud promises new levels of agility and cost-savings for Big Data, data warehousing and analytics. But it’s challenging to understand all the options – from IaaS and PaaS to newer services like HaaS (Hadoop as a Service) and BDaaS (Big Data as a Service). In her session at @BigDataExpo at @ThingsExpo, Hannah Smalltree, a director at Cazena, will provide an educational overview of emerging “as-a-service” options for Big Data in the cloud. This is critical background for IT and data profes...
Feb. 13, 2016 03:45 AM EST Reads: 250
One of the bewildering things about DevOps is integrating the massive toolchain including the dozens of new tools that seem to crop up every year. Part of DevOps is Continuous Delivery and having a complex toolchain can add additional integration and setup to your developer environment. In his session at @DevOpsSummit at 18th Cloud Expo, Miko Matsumura, Chief Marketing Officer of Gradle Inc., will discuss which tools to use in a developer stack, how to provision the toolchain to minimize onboa...
Feb. 12, 2016 09:00 PM EST Reads: 138
SYS-CON Events announced today that Interoute, owner-operator of one of Europe's largest networks and a global cloud services platform, has been named “Bronze Sponsor” of SYS-CON's 18th Cloud Expo, which will take place on June 7-9, 2015 at the Javits Center in New York, New York. Interoute is the owner-operator of one of Europe's largest networks and a global cloud services platform which encompasses 12 data centers, 14 virtual data centers and 31 colocation centers, with connections to 195 ad...
Feb. 12, 2016 04:15 PM EST Reads: 439
SYS-CON Events announced today that Commvault, a global leader in enterprise data protection and information management, has been named “Bronze Sponsor” of SYS-CON's 18th International Cloud Expo, which will take place on June 7–9, 2016, at the Javits Center in New York City, NY, and the 19th International Cloud Expo, which will take place on November 1–3, 2016, at the Santa Clara Convention Center in Santa Clara, CA. Commvault is a leading provider of data protection and information management...
Feb. 12, 2016 02:15 PM EST Reads: 466
With an estimated 50 billion devices connected to the Internet by 2020, several industries will begin to expand their capabilities for retaining end point data at the edge to better utilize the range of data types and sheer volume of M2M data generated by the Internet of Things. In his session at @ThingsExpo, Don DeLoach, CEO and President of Infobright, will discuss the infrastructures businesses will need to implement to handle this explosion of data by providing specific use cases for filte...
Feb. 12, 2016 01:00 PM EST Reads: 247
SYS-CON Events announced today that Pythian, a global IT services company specializing in helping companies adopt disruptive technologies to optimize revenue-generating systems, has been named “Bronze Sponsor” of SYS-CON's 18th Cloud Expo, which will take place on June 7-9, 2015 at the Javits Center in New York, New York. Founded in 1997, Pythian is a global IT services company that helps companies compete by adopting disruptive technologies such as cloud, Big Data, advanced analytics, and DevO...
Feb. 12, 2016 12:30 PM EST Reads: 275
SYS-CON Events announced today that Avere Systems, a leading provider of enterprise storage for the hybrid cloud, will exhibit at SYS-CON's 18th International Cloud Expo®, which will take place on June 7-9, 2016, at the Javits Center in New York City, NY. Avere delivers a more modern architectural approach to storage that doesn’t require the overprovisioning of storage capacity to achieve performance, overspending on expensive storage media for inactive data or the overbuilding of data centers ...
Feb. 12, 2016 12:30 PM EST Reads: 137
SYS-CON Events announced today that Alert Logic, Inc., the leading provider of Security-as-a-Service solutions for the cloud, will exhibit at SYS-CON's 18th International Cloud Expo®, which will take place on June 7-9, 2016, at the Javits Center in New York City, NY. Alert Logic, Inc., provides Security-as-a-Service for on-premises, cloud, and hybrid infrastructures, delivering deep security insight and continuous protection for customers at a lower cost than traditional security solutions. Ful...
Feb. 12, 2016 11:45 AM EST Reads: 465
The Quantified Economy represents the total global addressable market (TAM) for IoT that, according to a recent IDC report, will grow to an unprecedented $1.3 trillion by 2019. With this the third wave of the Internet-global proliferation of connected devices, appliances and sensors is poised to take off in 2016. In his session at @ThingsExpo, David McLauchlan, CEO and co-founder of Buddy Platform, will discuss how the ability to access and analyze the massive volume of streaming data from mil...
Feb. 12, 2016 09:00 AM EST
With the Apple Watch making its way onto wrists all over the world, it’s only a matter of time before it becomes a staple in the workplace. In fact, Forrester reported that 68 percent of technology and business decision-makers characterize wearables as a top priority for 2015. Recognizing their business value early on, FinancialForce.com was the first to bring ERP to wearables, helping streamline communication across front and back office functions. In his session at @ThingsExpo, Kevin Roberts...
Feb. 12, 2016 12:45 AM EST Reads: 423