Cheating with the 'ol dynamic language function alias trick
posted under category: ColdFusion on May 8, 2009 by Nathan
One of my favorite little tricks to play with CF, and with other dynamic languages like it, is aliasing function names.
Let’s say you have a component, User
, and a method, getIsUserNameValid()
. It’s a “getter” in order to satisfy some other kind of style requirement, but writing it out is verbose and feels wrong:
if (user.getIsUserNameValid()) {...}
You have to leave it as is so you don’t break any existing method calls, and to keep the basic style guidelines, but what if you could cheat a little? Consider this:
<cfset variables.isNameValid = variables.getIsUserNameValid />
<cfset this.isNameValid = this.getIsUserNameValid />
In ColdFusion, this creates an alias in the private "variables" scope as well as the public "this" scope to the old method. Now you can change your call to:
if (user.isNameValid()) {...}