|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 CollabNet, a global leader in enterprise software development, release automation and DevOps solutions, will be a Bronze Sponsor of SYS-CON's 20th International Cloud Expo®, taking place from June 6-8, 2017, at the Javits Center in New York City, NY. CollabNet offers a broad range of solutions with the mission of helping modern organizations deliver quality software at speed. The company’s latest innovation, the DevOps Lifecycle Manager (DLM), supports Value S...
Apr. 27, 2017 08:00 PM EDT Reads: 1,112
The Internet of Things is clearly many things: data collection and analytics, wearables, Smart Grids and Smart Cities, the Industrial Internet, and more. Cool platforms like Arduino, Raspberry Pi, Intel's Galileo and Edison, and a diverse world of sensors are making the IoT a great toy box for developers in all these areas. In this Power Panel at @ThingsExpo, moderated by Conference Chair Roger Strukhoff, panelists discussed what things are the most important, which will have the most profound e...
Apr. 27, 2017 07:45 PM EDT Reads: 2,297
Multiple data types are pouring into IoT deployments. Data is coming in small packages as well as enormous files and data streams of many sizes. Widespread use of mobile devices adds to the total. In this power panel at @ThingsExpo, moderated by Conference Chair Roger Strukhoff, panelists will look at the tools and environments that are being put to use in IoT deployments, as well as the team skills a modern enterprise IT shop needs to keep things running, get a handle on all this data, and deli...
Apr. 27, 2017 07:30 PM EDT Reads: 2,465
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...
Apr. 27, 2017 07:15 PM EDT Reads: 1,617
SYS-CON Events announced today that Grape Up will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct. 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Grape Up is a software company specializing in cloud native application development and professional services related to Cloud Foundry PaaS. With five expert teams that operate in various sectors of the market across the U.S. and Europe, Grape Up works with a variety of customers from emergi...
Apr. 27, 2017 06:45 PM EDT Reads: 2,205
The age of Digital Disruption is evolving into the next era – Digital Cohesion, an age in which applications securely self-assemble and deliver predictive services that continuously adapt to user behavior. Information from devices, sensors and applications around us will drive services seamlessly across mobile and fixed devices/infrastructure. This evolution is happening now in software defined services and secure networking. Four key drivers – Performance, Economics, Interoperability and Trust ...
Apr. 27, 2017 06:45 PM EDT Reads: 731
@ThingsExpo has been named the Most Influential ‘Smart Cities - IIoT' Account and @BigDataExpo has been named fourteenth by Right Relevance (RR), which provides curated information and intelligence on approximately 50,000 topics. In addition, Right Relevance provides an Insights offering that combines the above Topics and Influencers information with real time conversations to provide actionable intelligence with visualizations to enable decision making. The Insights service is applicable to eve...
Apr. 27, 2017 06:30 PM EDT Reads: 2,817
DevOps is often described as a combination of technology and culture. Without both, DevOps isn't complete. However, applying the culture to outdated technology is a recipe for disaster; as response times grow and connections between teams are delayed by technology, the culture will die. A Nutanix Enterprise Cloud has many benefits that provide the needed base for a true DevOps paradigm.
Apr. 27, 2017 06:00 PM EDT Reads: 1,034
Cybersecurity is a critical component of software development in many industries including medical devices. However, code is not always written to be robust or secure from the unknown or the unexpected. This gap can make medical devices susceptible to cybersecurity attacks ranging from compromised personal health information to life-sustaining treatment. In his session at @ThingsExpo, Clark Fortney, Software Engineer at Battelle, will discuss how programming oversight using key methods can incre...
Apr. 27, 2017 05:30 PM EDT Reads: 3,961
Most technology leaders, contemporary and from the hardware era, are reshaping their businesses to do software in the hope of capturing value in IoT. Although IoT is relatively new in the market, it has already gone through many promotional terms such as IoE, IoX, SDX, Edge/Fog, Mist Compute, etc. Ultimately, irrespective of the name, it is about deriving value from independent software assets participating in an ecosystem as one comprehensive solution.
Apr. 27, 2017 03:45 PM EDT Reads: 561
The 20th International Cloud Expo has announced that its Call for Papers is open. Cloud Expo, to be held June 6-8, 2017, at the Javits Center in New York City, brings together Cloud Computing, Big Data, Internet of Things, DevOps, Containers, 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 opportunity. Submit your speaking proposal ...
Apr. 27, 2017 01:45 PM EDT Reads: 1,304
New competitors, disruptive technologies, and growing expectations are pushing every business to both adopt and deliver new digital services. This ‘Digital Transformation’ demands rapid delivery and continuous iteration of new competitive services via multiple channels, which in turn demands new service delivery techniques – including DevOps. In this power panel at @DevOpsSummit 20th Cloud Expo, moderated by DevOps Conference Co-Chair Andi Mann, panelists will examine how DevOps helps to meet th...
Apr. 27, 2017 01:15 PM EDT Reads: 1,594
SYS-CON Events announced today that Juniper Networks (NYSE: JNPR), an industry leader in automated, scalable and secure networks, will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Juniper Networks challenges the status quo with products, solutions and services that transform the economics of networking. The company co-innovates with customers and partners to deliver automated, scalable and secure network...
Apr. 27, 2017 01:15 PM EDT Reads: 1,466
SYS-CON Events announced today that Hitachi, the leading provider the Internet of Things and Digital Transformation, will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Hitachi Data Systems, a wholly owned subsidiary of Hitachi, Ltd., offers an integrated portfolio of services and solutions that enable digital transformation through enhanced data management, governance, mobility and analytics. We help globa...
Apr. 27, 2017 12:45 PM EDT Reads: 1,309
SYS-CON Events announced today that T-Mobile will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. As America's Un-carrier, T-Mobile US, Inc., is redefining the way consumers and businesses buy wireless services through leading product and service innovation. The Company's advanced nationwide 4G LTE network delivers outstanding wireless experiences to 67.4 million customers who are unwilling to compromise on ...
Apr. 27, 2017 12:30 PM EDT Reads: 1,233
Five years ago development was seen as a dead-end career, now it’s anything but – with an explosion in mobile and IoT initiatives increasing the demand for skilled engineers. But apart from having a ready supply of great coders, what constitutes true ‘DevOps Royalty’? It’ll be the ability to craft resilient architectures, supportability, security everywhere across the software lifecycle. In his keynote at @DevOpsSummit at 20th Cloud Expo, Jeffrey Scheaffer, GM and SVP, Continuous Delivery Busine...
Apr. 27, 2017 12:30 PM EDT Reads: 1,064
20th Cloud Expo, taking place June 6-8, 2017, at the Javits Center in New York City, NY, 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.
Apr. 27, 2017 12:15 PM EDT Reads: 3,154
With major technology companies and startups seriously embracing IoT strategies, now is the perfect time to attend @ThingsExpo 2016 in New York. Learn what is going on, contribute to the discussions, and ensure that your enterprise is as "IoT-Ready" as it can be! Internet of @ThingsExpo, taking place June 6-8, 2017, at the Javits Center in New York City, New York, is co-located with 20th Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry p...
Apr. 27, 2017 12:15 PM EDT Reads: 1,234
With major technology companies and startups seriously embracing Cloud strategies, now is the perfect time to attend @CloudExpo | @ThingsExpo, June 6-8, 2017, at the Javits Center in New York City, NY and October 31 - November 2, 2017, Santa Clara Convention Center, CA. Learn what is going on, contribute to the discussions, and ensure that your enterprise is on the right path to Digital Transformation.
Apr. 27, 2017 12:00 PM EDT Reads: 1,344
SYS-CON Events announced today that SoftLayer, an IBM Company, has been named “Gold Sponsor” of SYS-CON's 18th Cloud Expo, which will take place on June 7-9, 2016, at the Javits Center in New York, New York. SoftLayer, an IBM Company, provides cloud infrastructure as a service from a growing number of data centers and network points of presence around the world. SoftLayer’s customers range from Web startups to global enterprises.
Apr. 27, 2017 10:45 AM EDT Reads: 2,211