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.


IoT & Smart Cities Stories
The challenges of aggregating data from consumer-oriented devices, such as wearable technologies and smart thermostats, are fairly well-understood. However, there are a new set of challenges for IoT devices that generate megabytes or gigabytes of data per second. Certainly, the infrastructure will have to change, as those volumes of data will likely overwhelm the available bandwidth for aggregating the data into a central repository. Ochandarena discusses a whole new way to think about your next...
DXWorldEXPO LLC announced today that Big Data Federation to Exhibit at the 22nd International CloudEXPO, colocated with DevOpsSUMMIT and DXWorldEXPO, November 12-13, 2018 in New York City. Big Data Federation, Inc. develops and applies artificial intelligence to predict financial and economic events that matter. The company uncovers patterns and precise drivers of performance and outcomes with the aid of machine-learning algorithms, big data, and fundamental analysis. Their products are deployed...
Dynatrace is an application performance management software company with products for the information technology departments and digital business owners of medium and large businesses. Building the Future of Monitoring with Artificial Intelligence. Today we can collect lots and lots of performance data. We build beautiful dashboards and even have fancy query languages to access and transform the data. Still performance data is a secret language only a couple of people understand. The more busine...
All in Mobile is a place where we continually maximize their impact by fostering understanding, empathy, insights, creativity and joy. They believe that a truly useful and desirable mobile app doesn't need the brightest idea or the most advanced technology. A great product begins with understanding people. It's easy to think that customers will love your app, but can you justify it? They make sure your final app is something that users truly want and need. The only way to do this is by ...
CloudEXPO | DevOpsSUMMIT | DXWorldEXPO are the world's most influential, independent events where Cloud Computing was coined and where technology buyers and vendors meet to experience and discuss the big picture of Digital Transformation and all of the strategies, tactics, and tools they need to realize their goals. Sponsors of DXWorldEXPO | CloudEXPO benefit from unmatched branding, profile building and lead generation opportunities.
Digital Transformation and Disruption, Amazon Style - What You Can Learn. Chris Kocher is a co-founder of Grey Heron, a management and strategic marketing consulting firm. He has 25+ years in both strategic and hands-on operating experience helping executives and investors build revenues and shareholder value. He has consulted with over 130 companies on innovating with new business models, product strategies and monetization. Chris has held management positions at HP and Symantec in addition to ...
Cell networks have the advantage of long-range communications, reaching an estimated 90% of the world. But cell networks such as 2G, 3G and LTE consume lots of power and were designed for connecting people. They are not optimized for low- or battery-powered devices or for IoT applications with infrequently transmitted data. Cell IoT modules that support narrow-band IoT and 4G cell networks will enable cell connectivity, device management, and app enablement for low-power wide-area network IoT. B...
The hierarchical architecture that distributes "compute" within the network specially at the edge can enable new services by harnessing emerging technologies. But Edge-Compute comes at increased cost that needs to be managed and potentially augmented by creative architecture solutions as there will always a catching-up with the capacity demands. Processing power in smartphones has enhanced YoY and there is increasingly spare compute capacity that can be potentially pooled. Uber has successfully ...
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...
When talking IoT we often focus on the devices, the sensors, the hardware itself. The new smart appliances, the new smart or self-driving cars (which are amalgamations of many ‘things'). When we are looking at the world of IoT, we should take a step back, look at the big picture. What value are these devices providing. IoT is not about the devices, its about the data consumed and generated. The devices are tools, mechanisms, conduits. This paper discusses the considerations when dealing with the...