| By Chip Temm | Article Rating: |
|
| December 9, 2006 12:00 PM EST | Reads: |
8,061 |
With the introduction of MX, ColdFusion programmers started to move away from the world of hard-to-maintain reams of scripts with includes, and into the world of clearly defined libraries with specific responsibilities. CustomTags were a good stab at re-usable code, but focused on the level of the function as opposed to grouping functions, which meant the method lacked a good way to define the return value and had scoping issues.
User defined functions (UDFs) gave us a clear return value, but still left us longing for classes. For several years now, we've had ColdFusion Components (CFCs) that give us a good chunk of the flexibility and power of object-oriented languages. Many have been honing their application programming interfaces (APIs) for years now, and the challenge has been to manage documentation and make the API usable to new developers joining the team, customers, or members of the CF community. Luckily, there is a language feature that can help us keep our documentation updated along with our code: component metadata. All of the attributes of the CFComponent, CFProperty, CFFunction, and CFArgument tags are available for us to view and use programmatically through reflection. We can ask components to tell us about themselves by passing an instance of them to CF's built-in getMetaData function.
<cfset example = createObject("component", "CFIDE.adminapi.administrator") />
<cfdump var="#getMetaData(example)#" />
In this article, we will explore ways of adding metadata to CFCs that can make your API easier to use.
One of the tenets of good API docs is that after reading them you should not be left with questions that can only be answered by reading the code. In some cases, the reader may not have access to the code. Even where the code is available, however, it's better left unread by API consumers. You want consumers of your API to code what is described (the interface) and not how it is done (implementation). When you encourage fellow developers to root around in your code, they may find ways to "optimize" their calls based on the internals of the functions. This can lead to reliance on "undocumented features," which were never really features at all. This practice violates the principle of information hiding in object-oriented programming. At the end of the day, the result can be brittleness - if you change your implementation, the client breaks.
If you use understandable names for your components, properties, functions, and arguments, and if you provide good type information (i.e., don't use the "any" type if possible), you are on your way to a good API. Names are important - think about them a lot. They provide the basic semantics of your API. Which has a clearer meaning: Person.getAgeYears() or Person.calcYears()? If you provide a description of every element (CFC, property, function, or argument) of your API using the hint attribute, you will have built a much more understandable system. Hints should explain more than the name can by itself. >From hints, consumers should get enough information to determine the right element for the use intended.
There are a number of types of information embedded in hints that you can see when scanning API docs. Sometimes usage information is there - we all like snippets or examples. We often see information on enumerated values for function arguments or returns. For example, ColdFusion's own administrative API's CFIDE.adminapi.base class has a function called getEdition, which the hint states can return the values "Developer, Evaluation, Standard, Enterprise, and Professional." On the flip side, CFIDE.adminapi.administrator has a function called setAdminProperty with an argument propertyName, which the hint states can only accept the values "migrationFlag, MXMigrationFlag, SetupWizardFlag, migrateCF5, migrateCF6, setupOdbc, and setupEnabldRds." There are other examples such as authorship (some classes may have a lot of functions contributed by many different authors), validity ("this function deprecated as of version 1.4"), and the ever-present TODO. All of these types of information can be broken out into their own metadata fields if you desire. One of the benefits of doing so is to assist in extracting different kinds of documentation from the code. Creating a new metadata field is as simple as adding it as a new attribute to your CFComponent, CFProperty, CFFunction, or CFargument tag. This worked in CF6, but is actually a documented feature of CF7! For the purpose of this article, we'll focus on the enumerated values example, as this is a metadata element that can contribute to different kinds of automation related to the documented code, such as testing. (Java5 programmers bear with us - CF has no enumerated types.)
Decomposing Metadata
If the hint for CFIDE.adminapi.base.setAdminProperty's propertyName argument tells us that it can only accept one of seven values, that's important information for client code to have, which it will use to adapt accordingly. What if a new version of CF was released that exposed more admin properties? Would our client code automatically cope? Imagine a CFCUnit test stub generator. If it could discover the range of allowed values programmatically, it could do more work for you - testing both in-range and out-of-range values.
Looking at the hint for setAdminProperty, we can decompose it into two kinds of information: a description about what the function does and an enumeration of potential return values. The existing hint attribute is meant to handle the description, but we could add our own new attribute inputRange and set its value to a list. Note: the example is hypothetical as this CFC is not editable.
<cffunction name="setAdminProperty" ... >
<cfargument
name="propertyName"
hint="Return Migration or setup flag to be set."
return="string"
inputRange="migrationFlag, MXMigrationFlag, SetupWizardFlag,
migrateCF5, migrateCF6, setupSampleApps, setupOdbc,
setupEnabldRds"
>
Now, we can see the changed metadata for the argument if we cfdump the result of a getMetadata call, as shown in Figure 1.
The trick is to remember that there is no way to reference by name the metadata nested in the PARAMETERS array shown in Figure 1. You have to know the position of the argument in the array to access it. This is a pain. I have a utility called simplifyMetadata (see Listing 1) that converts all the nested arrays to structs, which allows easier access to nested information. After running the metadata through, what we end up with is shown in Figure 2.
Now we have a value that we can programmatically access, which will tell us all possible input values for this function:
<cfscript>
adminAPI = createObject("component", "CFIDE.adminapi.administrator");
metadata = getMetadata(adminAPI);
simpleMetadata = simplifyMetadata(metadata);//custom function to convert nested arrays
</cfscript>
<cfoutput>
The input range for the setAdminProperty function of CFIDE.adminapi.administrator is:
simpleMetadata.functions.setAdminProperty.parameters.propertyName.inputRange#
</cfoutput>
Driving Validation with Metadata
An interesting way to use this type of metadata about input ranges is to use it to help drive data validation for the argument. Let's say we have the function convertColorToHex(string colorName) in a CFC called UtilityClass. We want to inform the clients of this function that we only know how to convert Red, Green, and Blue. We can define the new metadata attribute called inputRange to expose this in a sensible way.
We can see in Listing 2 that while consumers of the function can see the input range without reading the code, the function itself does not validate the input range. If out-of-range input is sent, the function will err by saying "struct key does not exist."
To validate input, we can insert a check after we set up our color structure:
...
if(not structKeyExists(_colorStruct, arguments.colorName)){
return "";
}
...
This, however, violates the expectation of the client according to the hint: emptystring is not a hexadecimal value. We should probably throw an exception instead (another thing we can document using metadata later). But we have another problem, too. When we make changes to the code, we may have to update the inputRange to let consumers know we are supporting more colors. What if changing our inputRange was all we had to do in order to make our validation correct? Let's revise the method definition by inserting the following between line 14 & 15:
<cfset var _metadata = simplifyMetadata (getMetaData("#this#")) />
<cfset var _range =
metadata.functions.convertColorToHex.parameters.colorName.inputRange />
<cfif not listfindnocase(arguments.colorName, _range)>
<cfthrow type="valueOutOfRangeException" >
</cfif>
Now when we change the inputRange attribute on the colorName argument, the validation rule changes its behavior too. Metadata driving function - pretty cool. The performance-minded among you are asking what this coolness costs? Hardly anything, in fact. We already have an instance of the component loaded into memory (there are no static classes in CF so the only way to call our function is from an instance), and the getMetaData call takes so little time that it will usually come out as 0ms in your trace. If you build a function like simplifyMetadata, running that will cost you, as it will recurse through the metadata to simplify it. For speed, you could just rely on the getMetaData call alone.
Now we have the potential for our function to throw a valueOutOfRangeException if someone passes an unacceptable value. However, our client doesn't know that without reading the code. We can include another metadata attribute - throws:
1 <cffunction
2 name="convertColorToHex"
3 return="string"
4 access="public"
5 throws="valueOutOfRangeException"
6 hint= "Accepts an English color name and returns
7 the corresponding six character hexadecimal."
8 >
Now our client has documentation for the possible exception and can determine how to deal with the event that it is thrown. Listing 3 brings all of the topics discussed together.
Conclusion
This article assumes that you standardize on a set of clearly defined and meaningful extra metadata attributes that are used consistently across your project(s) by all members of your team. Without consistency, your API consumers won't be able to rely on the metadata. "Was that attribute named inputRange or allowedValues?" Code templates/wizards are a good approach to such standardization. Once you have standardized, you may want to alter the component browser that ships with CF to expose your new standard attributes there, as it makes extensive use of getMetadata to extract useful information from CFCs. This is not hard, as Adobe has been kind enough to leave the code unencrypted.
If you haven't checked it out, open up a browser and navigate to cf_root/wwwroot/CFIDE/componentutils/componentdoc.cfm. As shown in Figure 3, you will see three panes: the upper left pane is a list of all CFC packages (directories containing CFCs); the lower left pane is a list of the components living inside of the package selected in the upper left pane; and the right pane is a description of the CFC itself.
I hope that you have found this discussion of component metadata interesting. I encourage you to experiment with this. There is a lot that you can do programmatically in this area. I have, for example, enabled rudimentary Interfaces by defining an implements attribute on CFCs. Overall, the biggest benefit to the practice of extending metadata will accrue to larger teams and those interested in generating metrics, documentation, or other code (such as test stubs) on the basis of the metadata.
Published December 9, 2006 Reads 8,061
Copyright © 2006 SYS-CON Media, Inc. — All Rights Reserved.
Syndicated stories and blog feeds, all rights reserved by the author.
More Stories By Chip Temm
Over the past decade, Chip Temm moved from North America to Europe and on to Africa where his company anthroLogik solutions provided analysis and development services to non-governmental organizations across seven timezones. He is currently back in Washington, DC where "remote development" means working from home and "wildlife" means raccoon.
- Adobe’s Aiming ColdFusion at Multiple Clouds
- Cloud Computing Journal: Adobe to Deliver ColdFusion in the Cloud
- Adobe Reader Sued
- Adobe May Cooperate with Apple to Transplant Flash Player to iPhone
- Adobe Flex Developer Earns $100K in New York City
- Adobe LiveCycle Enterprise Suite 2 for Cloud Computing
- Adobe Cans Another 9% of its Workforce
- Adobe Betas Target RIAs and Cloud Computing
- Adobe MAX 2009 Online
- Thinking of Flex in London
- Moyea DVD4Web Converter V2.0 Converts DVD to FLV Fast and Synchronously with Watermarks
- Adobe & Salesforce Cut Cloud Deal
- Adobe’s Aiming ColdFusion at Multiple Clouds
- Eval JavaScript in a Global Context
- Fig Leaf Software to Exhibit at Government IT Conference & Expo
- Is Microsoft as Free as Open Source?
- Cloud Computing Journal: Adobe to Deliver ColdFusion in the Cloud
- Adobe Reader Sued
- The Planet Named “Bronze Sponsor” of Cloud Computing Expo
- Microsoft Expression Web Has Got Game
- Adobe May Cooperate with Apple to Transplant Flash Player to iPhone
- Bruce Chizen Joins Voyager Capital as Venture Partner
- My Top Seven Wishes From Adobe MAX 2009
- Adobe Flex Developer Earns $100K in New York City
- The Next Programming Models, RIAs and Composite Applications
- Where Are RIA Technologies Headed in 2008?
- Constructing an Application with Flash Forms from the Ground Up
- AJAX World RIA Conference & Expo Kicks Off in New York City
- CFEclipse: The Developer's IDE, Eclipse For ColdFusion
- Personal Branding Checklist
- Adobe Flex 2: Advanced DataGrid
- Has the Technology Bounceback Begun?
- Building a Zip Code Proximity Search with ColdFusion
- i-Technology Viewpoint: We Need Not More Frameworks, But Better Programmers
- The Asynchronous CFML Gateway
- Web Services Using ColdFusion and Apache CXF





































