You will be redirected in 30 seconds or close now.

ColdFusion Authors: Yakov Fain, Jeremy Geelan, Maureen O'Gara, Nancy Y. Nee, Tad Anderson

Related Topics: ColdFusion

ColdFusion: Article

Extending Component Metadata for Enhanced Documentation

Making your API easier to use

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" ... >
hint="Return Migration or setup flag to be set."
inputRange="migrationFlag, MXMigrationFlag, SetupWizardFlag,
migrateCF5, migrateCF6, setupSampleApps, setupOdbc,

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:

    adminAPI = createObject("component", "CFIDE.adminapi.administrator");
    metadata = getMetadata(adminAPI);
    simpleMetadata = simplifyMetadata(metadata);//custom function to convert nested arrays

The input range for the setAdminProperty function of CFIDE.adminapi.administrator is:


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" >

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.

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.

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 organizations across seven timezones. He is currently back in Washington, DC where "remote development" means working from home and "wildlife" means raccoon.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.

@ThingsExpo Stories
DX World EXPO, LLC, a Lighthouse Point, Florida-based startup trade show producer and the creator of "DXWorldEXPO® - Digital Transformation Conference & Expo" has announced its executive management team. The team is headed by Levent Selamoglu, who has been named CEO. "Now is the time for a truly global DX event, to bring together the leading minds from the technology world in a conversation about Digital Transformation," he said in making the announcement.
"Space Monkey by Vivent Smart Home is a product that is a distributed cloud-based edge storage network. Vivent Smart Home, our parent company, is a smart home provider that places a lot of hard drives across homes in North America," explained JT Olds, Director of Engineering, and Brandon Crowfeather, Product Manager, at Vivint Smart Home, in this SYS-CON.tv interview at @ThingsExpo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
SYS-CON Events announced today that Conference Guru has been named “Media Sponsor” of the 22nd International Cloud Expo, which will take place on June 5-7, 2018, at the Javits Center in New York, NY. A valuable conference experience generates new contacts, sales leads, potential strategic partners and potential investors; helps gather competitive intelligence and even provides inspiration for new products and services. Conference Guru works with conference organizers to pass great deals to gre...
The Internet of Things will challenge the status quo of how IT and development organizations operate. Or will it? Certainly the fog layer of IoT requires special insights about data ontology, security and transactional integrity. But the developmental challenges are the same: People, Process and Platform. In his session at @ThingsExpo, Craig Sproule, CEO of Metavine, demonstrated how to move beyond today's coding paradigm and shared the must-have mindsets for removing complexity from the develop...
In his Opening Keynote at 21st Cloud Expo, John Considine, General Manager of IBM Cloud Infrastructure, led attendees through the exciting evolution of the cloud. He looked at this major disruption from the perspective of technology, business models, and what this means for enterprises of all sizes. John Considine is General Manager of Cloud Infrastructure Services at IBM. In that role he is responsible for leading IBM’s public cloud infrastructure including strategy, development, and offering m...
"Evatronix provides design services to companies that need to integrate the IoT technology in their products but they don't necessarily have the expertise, knowledge and design team to do so," explained Adam Morawiec, VP of Business Development at Evatronix, in this SYS-CON.tv interview at @ThingsExpo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
To get the most out of their data, successful companies are not focusing on queries and data lakes, they are actively integrating analytics into their operations with a data-first application development approach. Real-time adjustments to improve revenues, reduce costs, or mitigate risk rely on applications that minimize latency on a variety of data sources. In his session at @BigDataExpo, Jack Norris, Senior Vice President, Data and Applications at MapR Technologies, reviewed best practices to ...
Widespread fragmentation is stalling the growth of the IIoT and making it difficult for partners to work together. The number of software platforms, apps, hardware and connectivity standards is creating paralysis among businesses that are afraid of being locked into a solution. EdgeX Foundry is unifying the community around a common IoT edge framework and an ecosystem of interoperable components.
Large industrial manufacturing organizations are adopting the agile principles of cloud software companies. The industrial manufacturing development process has not scaled over time. Now that design CAD teams are geographically distributed, centralizing their work is key. With large multi-gigabyte projects, outdated tools have stifled industrial team agility, time-to-market milestones, and impacted P&L stakeholders.
"Akvelon is a software development company and we also provide consultancy services to folks who are looking to scale or accelerate their engineering roadmaps," explained Jeremiah Mothersell, Marketing Manager at Akvelon, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
"IBM is really all in on blockchain. We take a look at sort of the history of blockchain ledger technologies. It started out with bitcoin, Ethereum, and IBM evaluated these particular blockchain technologies and found they were anonymous and permissionless and that many companies were looking for permissioned blockchain," stated René Bostic, Technical VP of the IBM Cloud Unit in North America, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Conventi...
In his session at 21st Cloud Expo, Carl J. Levine, Senior Technical Evangelist for NS1, will objectively discuss how DNS is used to solve Digital Transformation challenges in large SaaS applications, CDNs, AdTech platforms, and other demanding use cases. Carl J. Levine is the Senior Technical Evangelist for NS1. A veteran of the Internet Infrastructure space, he has over a decade of experience with startups, networking protocols and Internet infrastructure, combined with the unique ability to it...
22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo 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 ...
"Cloud Academy is an enterprise training platform for the cloud, specifically public clouds. We offer guided learning experiences on AWS, Azure, Google Cloud and all the surrounding methodologies and technologies that you need to know and your teams need to know in order to leverage the full benefits of the cloud," explained Alex Brower, VP of Marketing at Cloud Academy, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clar...
Gemini is Yahoo’s native and search advertising platform. To ensure the quality of a complex distributed system that spans multiple products and components and across various desktop websites and mobile app and web experiences – both Yahoo owned and operated and third-party syndication (supply), with complex interaction with more than a billion users and numerous advertisers globally (demand) – it becomes imperative to automate a set of end-to-end tests 24x7 to detect bugs and regression. In th...
"MobiDev is a software development company and we do complex, custom software development for everybody from entrepreneurs to large enterprises," explained Alan Winters, U.S. Head of Business Development at MobiDev, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
Coca-Cola’s Google powered digital signage system lays the groundwork for a more valuable connection between Coke and its customers. Digital signs pair software with high-resolution displays so that a message can be changed instantly based on what the operator wants to communicate or sell. In their Day 3 Keynote at 21st Cloud Expo, Greg Chambers, Global Group Director, Digital Innovation, Coca-Cola, and Vidya Nagarajan, a Senior Product Manager at Google, discussed how from store operations and ...
"There's plenty of bandwidth out there but it's never in the right place. So what Cedexis does is uses data to work out the best pathways to get data from the origin to the person who wants to get it," explained Simon Jones, Evangelist and Head of Marketing at Cedexis, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
SYS-CON Events announced today that CrowdReviews.com has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5–7, 2018, at the Javits Center in New York City, NY. CrowdReviews.com is a transparent online platform for determining which products and services are the best based on the opinion of the crowd. The crowd consists of Internet users that have experienced products and services first-hand and have an interest in letting other potential buye...
SYS-CON Events announced today that Telecom Reseller has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5-7, 2018, at the Javits Center in New York, NY. 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.