Welcome!

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

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
Michael Maximilien, better known as max or Dr. Max, is a computer scientist with IBM. At IBM Research Triangle Park, he was a principal engineer for the worldwide industry point-of-sale standard: JavaPOS. At IBM Research, some highlights include pioneering research on semantic Web services, mashups, and cloud computing, and platform-as-a-service. He joined the IBM Cloud Labs in 2014 and works closely with Pivotal Inc., to help make the Cloud Found the best PaaS.
Cloud-enabled transformation has evolved from cost saving measure to business innovation strategy -- one that combines the cloud with cognitive capabilities to drive market disruption. Learn how you can achieve the insight and agility you need to gain a competitive advantage. Industry-acclaimed CTO and cloud expert, Shankar Kalyana presents. Only the most exceptional IBMers are appointed with the rare distinction of IBM Fellow, the highest technical honor in the company. Shankar has also receive...
"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.
Business professionals no longer wonder if they'll migrate to the cloud; it's now a matter of when. The cloud environment has proved to be a major force in transitioning to an agile business model that enables quick decisions and fast implementation that solidify customer relationships. And when the cloud is combined with the power of cognitive computing, it drives innovation and transformation that achieves astounding competitive advantage.
The Founder of NostaLab and a member of the Google Health Advisory Board, John is a unique combination of strategic thinker, marketer and entrepreneur. His career was built on the "science of advertising" combining strategy, creativity and marketing for industry-leading results. Combined with his ability to communicate complicated scientific concepts in a way that consumers and scientists alike can appreciate, John is a sought-after speaker for conferences on the forefront of healthcare science,...
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, discussed the key considerations around quality, volume, timeliness, and pedigree that must be dealt with in order to properly fuel that engine.
Explosive growth in connected devices. Enormous amounts of data for collection and analysis. Critical use of data for split-second decision making and actionable information. All three are factors in making the Internet of Things a reality. Yet, any one factor would have an IT organization pondering its infrastructure strategy. How should your organization enhance its IT framework to enable an Internet of Things implementation? In his session at @ThingsExpo, James Kirkland, Red Hat's Chief Archi...
The current age of digital transformation means that IT organizations must adapt their toolset to cover all digital experiences, beyond just the end users’. Today’s businesses can no longer focus solely on the digital interactions they manage with employees or customers; they must now contend with non-traditional factors. Whether it's the power of brand to make or break a company, the need to monitor across all locations 24/7, or the ability to proactively resolve issues, companies must adapt to...
In his keynote at 18th Cloud Expo, Andrew Keys, Co-Founder of ConsenSys Enterprise, provided an overview of the evolution of the Internet and the Database and the future of their combination – the Blockchain. Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life settl...
Organizations planning enterprise data center consolidation and modernization projects are faced with a challenging, costly reality. Requirements to deploy modern, cloud-native applications simultaneously with traditional client/server applications are almost impossible to achieve with hardware-centric enterprise infrastructure. Compute and network infrastructure are fast moving down a software-defined path, but storage has been a laggard. Until now.
In his general session at 19th Cloud Expo, Manish Dixit, VP of Product and Engineering at Dice, discussed 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 at D...
DXWorldEXPO LLC announced today that the upcoming DXWorldEXPO | CloudEXPO New York event will feature 10 companies from Poland to participate at the "Poland Digital Transformation Pavilion" on November 12-13, 2018.
Digital Transformation is much more than a buzzword. The radical shift to digital mechanisms for almost every process is evident across all industries and verticals. This is often especially true in financial services, where the legacy environment is many times unable to keep up with the rapidly shifting demands of the consumer. The constant pressure to provide complete, omnichannel delivery of customer-facing solutions to meet both regulatory and customer demands is putting enormous pressure on...
The best way to leverage your CloudEXPO | DXWorldEXPO presence as a sponsor and exhibitor is to plan your news announcements around our events. The press covering CloudEXPO | DXWorldEXPO 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 CloudEXPO. Product announcements during our show provide your company with the most reach through our targeted audienc...
JETRO showcased Japan Digital Transformation Pavilion at SYS-CON's 21st International Cloud Expo® at the Santa Clara Convention Center in Santa Clara, CA. The Japan External Trade Organization (JETRO) is a non-profit organization that provides business support services to companies expanding to Japan. With the support of JETRO's dedicated staff, clients can incorporate their business; receive visa, immigration, and HR support; find dedicated office space; identify local government subsidies; get...
DXWorldEXPO LLC announced today that All in Mobile, a mobile app development company from Poland, will exhibit at the 22nd International CloudEXPO | DXWorldEXPO. All In Mobile is a mobile app development company from Poland. Since 2014, they maintain passion for developing mobile applications for enterprises and startups worldwide.
@DevOpsSummit at Cloud Expo, taking place November 12-13 in New York City, NY, is co-located with 22nd international CloudEXPO | first international DXWorldEXPO and will feature technical sessions from a rock star conference faculty and the leading industry players in the world.
"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.
As data explodes in quantity, importance and from new sources, the need for managing and protecting data residing across physical, virtual, and cloud environments grow with it. Managing data includes protecting it, indexing and classifying it for true, long-term management, compliance and E-Discovery. Commvault can ensure this with a single pane of glass solution – whether in a private cloud, a Service Provider delivered public cloud or a hybrid cloud environment – across the heterogeneous enter...
DXWorldEXPO LLC announced today that ICC-USA, a computer systems integrator and server manufacturing company focused on developing products and product appliances, will exhibit at the 22nd International CloudEXPO | DXWorldEXPO. DXWordEXPO New York 2018, colocated with CloudEXPO New York 2018 will be held November 11-13, 2018, in New York City. ICC is a computer systems integrator and server manufacturing company focused on developing products and product appliances to meet a wide range of ...