Shortcut Functions in CFML

Create shortcuts to long-named functions: variables.__ = intermediateFunction;

TL;DR Create shortcuts to long-named functions: variables.__ = intermediateFunction;

For a recent project at work, I found that a function I was going to be calling a lot had a very long name. The function was a translation look-up. I pass in a string which represents a language key, and the function returns a value for the target language.

Because our project is heavily translated, it meant I’d be calling the method many times per page. It would going to be a lot of extra typing. The solution we found, to reduce that typing to a minimum, is something I’m calling “shortcut functions”.

Shortcut functions take three parts: the original function, an intermediate function, and the assignment of the shortcut function. With a shortcut function, you can go from writing application.translations.getTranslation( string ) to __( string ).

Don’t give me that look. That’s pretty cool.

  1. You should already have your original function. Chances are, it lives in another CFC somewhere, and that’s why you want to shortcut the name.
  2. Next you have to write your intermediate function. The goal of this function is to call your original function. We need this intermediate function to preserve the scoping of the original function. I like the pattern shortcutOriginalFunction. Your intermediate function can be an anonymous function, too, which might be less confusing for some people.
  3. Finally, you write your assignment. The assignment puts the intermediate function into the variables scope, so we can call it without an explicit scope. The assignment needs to go into the onRequest method of your Application.cfc and should not use parentheses. It should look something like this: variables.__ = intermediateFunction;

Let’s look at some code. Included is an index.cfm, a translation CFC (which contains our original function), and the Application.cfc that works our magic. This code has only been tested on Adobe ColdFusion 10.

Author: Miles Rausch

I've made a smart playlist of all the songs with 0 plays. I listen to them because I feel bad for them not because I like the music. I'm THAT guy.